#include <stdio.h>
#include <stdlib.h>
char **Names;
int size = 2; //Minimum size for 2D array
void main() {
int i;
Names = (char **)malloc(size * sizeof(char *)); // First initaliaion of 2D array in heap
for (i = 0; i < size; i++)
Names[i] = (char *)malloc(20 * sizeof(char));
printf("\nenter");
for (i = 0; i < size; i++)
scanf("%s", Names[i]);
while (1) {
size++;
Names = (char **)realloc(Names, size * sizeof(char *)); //Dynamic allocation of 2D aray
for (i = 0; i < size; i++)
Names[i] = (char *)realloc(Names[i], 20 * sizeof(char));
i = size - 1;
printf("\nenter");
scanf("%s", Names[i]);
for (i = 0; i < size; i++)
printf("\n%s", Names[i]);
}
}
It doesn't crash immediately it depends on the "size" I initialized. It crashes after 5 allocations for me. I tried adding free function but it did not seem to help.
scanf("%s"toscanf("%19s"Names[i], since the new size is the same as the old one.void main()is non-portable; unless you are running the program on a platform which cannot accept a return value for a program (e.g., some embedded systems), you should always useint main()and end the function withreturn 0orreturn <error-code>. Second, casting the return values ofmalloc()/realloc()is not necessary in C, and considered non-idiomatic.