If I have a char *null_terminated_array="hello"
, I think printf("%zu",strlen(null_terminated_array))
should print 5
(not including '\0'
) and not 6
(including '\0'
).
CodePudding user response:
Yes that is what you would expect.
Just be cautious if you were tempted to use sizeof
rather than strlen
on the array:
char *null_terminated_array="hello";
char char_array[6]="hello";
printf("null_terminated_array = %s\n",null_terminated_array);
printf("strlen(null_terminated_array) = %zu\n",strlen(null_terminated_array));
printf("sizeof(null_terminated_array) = %zu\n",sizeof(null_terminated_array));
printf("\n");
printf("char_array = %s\n",char_array);
printf("strlen(char_array) = %zu\n",strlen(char_array));
printf("sizeof(char_array) = %zu\n",sizeof(char_array));
for the platform that I ran this on this gives
null_terminated_array = hello
strlen(null_terminated_array) = 5
sizeof(null_terminated_array) = 8
char_array = hello
strlen(char_array) = 5
sizeof(char_array) = 6
The apparent discrepancy for sizeof(null_terminated_array)
is to do with automatic memory allocation using blocks of 32bits (platform dependent).