c - How is sizeof(char *) and sizeof(char) different? -


#include<stdio.h> main() {     char *str[]= {"frogs","do","not","die","they","croak"};     printf("%d %d %d",sizeof(str),sizeof(str[0]),sizeof(char)); } 

output is:

48 8 1

according size of char being 1 byte , there 6 character variables total size of array should 6 instead of 48!

point 1

sizeof retruns size of data type, not amount of memory allocated variable.

for it's worth, if want measure length of string, (i.e., number of elements inside string), can use strlen()

point 2

don't confused datatypes.

  • str array of pointers. holds 6 pointers, sizeof give 6 * sizeof(<pointer type>) 6 * 8 or 48 on 64-bit systems.
  • str[0] pointer, sizeof str[0] equals sizeof(char *) 8 on 64-bit systems.
  • c standard guarantees sizeof(char) equal 1.

point 3

sizeof operator returns size_t. need use %zu format specifier print portably , reliably.


Comments