I decided to conduct a version of the challenge using strings. Here is my code:
// Created by Keith Jones on 8/13/14.
// Copyright © 2014 Keith Jones. All rights reserved.
int main(int argc, const char * argv)
char *str = "Hi Mom"; printf("String = %s\n", str); printf("Length of string is %zu\n", sizeof("Hi Mom")); printf("Length of string is %zu\n", sizeof(str)); printf("Length of string is %zu\n\n", sizeof(*str)); return EXIT_SUCCESS;
Here is the resultant output:
String = Hi Mom
Length of string is 7
Length of string is 8
Length of string is 1
Program ended with exit code: 0
I found this result odd. My hypothesis is that
printf(“Length of string is %zu\n”, sizeof(“Hi Mom”)); counts the characters in the string not including a string termination character
printf(“Length of string is %zu\n”, sizeof(str)); counts the number of characters in the string plus a string termination character
printf(“Length of string is %zu\n\n”, sizeof(*str)); counts only the first character in the string
I don’t know that there is a string termination character. I am inferring that there is because it would be necessary to identify the end of the string when the string is referenced by pointer. When the string is a constant string, the termination character would not be necessary since the end of the string is deterministic. I am correct or way off base? Any alternate explanations of the results of this experiment?