I tried to create one array of strings in C. Here is the code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main()
{
char *foo[100];
strcpy(foo[0], "Testing this");
printf("%s ", foo[0]);
return 1;
}
But when I compile it, it simply breaks. No error, no nothing, it simply doesn’t work and breaks. Any suggestion? When I tri char *foo[10] it works, but I can’t work with just 10 strings
You allocated an array of pointers but did not allocate any memory for them to point to. You need to call
mallocto allocate memory from the heap.Naturally you would need to
freethe memory at some later date when you were finished with it.Your code invokes what is known as undefined behavior. Basically anything can happen, including the code working as you intended. If the version with
char *foo[10]works as you intended that’s simply down to luck.As an aside, your
main()definition is wrong. It should beint main(void).