I'm having this weird issue. I've looked on other Stack Overflow posts, but they're dealing with large arrays that wouldn't affect anything with my code. They've recommended malloc()
but it would be useless on something as small as this.
I'm practicing with C, and a simple thing like this:
int main()
{
char* things[] = {"test1\n", "test2\n", "test3\n"};
for (long unsigned int i = 0; i < sizeof(things) - 1; i )
{
printf(things[i]);
}
return 0;
}
Gives a segmentation fault. It actually does end up printing test1, test2, test3, though. After it's done with that it gives a segmentation fault. What am I doing wrong?
CodePudding user response:
The actual value of sizeof(things)
will surprise you. Find it out.
As user stark explains:
sizeof is the total size in bytes of things, which is likely 3*8 or 24.
To be more explicit, it it not the number of characters in your quasi-strings, it is the size of pointers in your environment times 3.
So the solution is to divide the total by the size of one:
sizeof(things)/sizeof(things[0])
.