Different answers from strlen and sizeof for Pointer & Array based init of String [duplicate]

Because sizeof gives you the size in bytes of the data type. The data type of str1 is char* which 4 bytes. In contrast, strlen gives you the length of the string in chars not including the null terminator, thus 7. The sizeof str2 is char array of 8 bytes, which is the number of chars including the null terminator.

See this entry from the C-FAQ: http://c-faq.com/~scs/cclass/krnotes/sx9d.html

Try this:

 char str2[8];
 strncpy(str2, "Sanjeev", 7);
 char *str1 = str2;
 printf("%d %d\n",strlen(str1),sizeof(str1));    
 printf("%d %d\n",strlen(str2),sizeof(str2));

str1 is a pointer to char and size of a pointer variable on your system is 4.
str2 is a array of char on stack, which stores 8 characters, "s","a","n","j","e","e","v","\0" so its size is 8

Important to note that size of pointer to various data type will be same, because they are pointing to different data types but they occupy only size of pointer on that system.


sizeof(str1) is sizeof(char*)
whereas sizeof str2 is sizeof(char array)

sizeof(char array) should be equal to strlen(char array) + 1 (NULL termination).
Well if you pass the char array to a function, its size as shown by sizeof will change. The reason is char array is passed as char* only.


 char *str1 = "Sanjeev";
 printf("%d %d\n",strlen(str1),sizeof(str1)); 

strlen() gives the length of the string which is 7. sizeof() is a compile time operator and sizeof(str1) gives the size of pointer on your implementation (i.e 4).

char str2[] = "Sanjeev";  
printf("%d %d\n",strlen(str2),sizeof(str2));

sizeof(str2) gives the size of the array which is 8*sizeof(char) i.e. 8 [including the NUL terminator]