If I have a string:
char s1[]="hello, how are you?";
printf("%d\n",sizeof(s1));
it prints the exact, right number of characters, 20. But if I have a string initialized by a pointer:
char *s2;
s2=(char*)malloc(sizeof(char));
strcpy(s2,s1);
printf("%d\n",sizeof(s2));
it prints the size of a pointer, which depends on the machine (on mine, 8).
So why is it 8 bytes for s2, and 20 bytes for s1, since they are the same string?
They are not the same string, or even the same type.
char s2[]is an array, it has the size of the sum of the size of its elements.char *s2is a pointer, it has the size of a pointer.sizeof()is (in C89) a compile-time operator that must know the size of it’s argument at compile time. Since a pointer can come from anywhere,sizeof()can’t know the size of the allocated memory, but an array is always given a size at compile time (except for C99’s VLA’s), andsizeof()can then return the size of that memory.