M
MQ
[email protected] said:Hi,
I have a question about string constants. I compile the following program:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[] = "\007";
char str2[] = "\0" "07";
char str3[] = { '\0', '0', '7', '\0' };
printf("str1 = %s\n" "str2 = %s\n" "str3 = %s\n", str1, str2, str3);
printf("sizeof(str1) = %d\n" "sizeof(str2) = %d\n"
"sizeof(str3) = %d\n", sizeof(str1), sizeof(str2),
sizeof(str3));
printf("strlen(str1) = %d\n" "strlen(str2) = %d\n"
"strlen(str3) = %d\n", strlen(str1), strlen(str2),
strlen(str3));
return 0;
}
Here is the output:
str1 =
str2 =
str3 =
sizeof(str1) = 2
sizeof(str2) = 4
sizeof(str3) = 4
strlen(str1) = 1
strlen(str2) = 0
strlen(str3) = 0
I understand that yet another obscure C feature is the octal character
specification so that \ddd is one character. However, should not str1 and str2
be the same?
No, str1 contains a single ASCII character with value 7, followed by a
null terminator, which gives a length of two. str2 is actually three
characters, which are '\0', which is a null terminator character,
followed by the '0' character, followed by the '7' character. With the
null terminator at the end of the string, you have four characters.
str1 appears invisible because ASCII 7 is a non-printable character.
In str2 and str3 you have actually created a string which starts with a
null terminator, making the string appear to be empty (which is why
strlen returns 0 in both of these cases)