Possible Duplicate:
Question about pointers and strings in C
#include<stdio.h>
int main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d\n",sizeof(str1),sizeof(str2),sizeof("abcd"));
return 0;
}
Why does this code give same answers for sizeof(str2) and sizeof("abcd") even when str2 is ideally just like a pointer to a string , as is str1 ,so answer should be 4 4 5
Code on Ideone:
http://ideone.com/za8aV
Answer: 4 5 5
Where did you get the idea that
str2is “ideally just like a pointer to a string”? It is not.str2is an array. When operatorsizeofis applied to an array, it returns the size of the array object in bytes.String literal is also an array, so when
sizeofis applied to a string literal, it returns the size of that array object in bytes. So, it is perfectly natural to expectsizeof("abcd")andsizeof(str2)to produce the same result. And they do.P.S.
%dis not an appropriate format specifier to print the result ofsizeof.%drequiresintargument, whilesizeofproduces asize_tvalue. Use%zuto print values ofsize_ttype.