Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

c - Behaviour of sizeof with string

?#?include? <stdio.h>
#include <string.h>
int main()
{
    printf("%d
",sizeof("S65AB"));
    printf("%d
",sizeof("S65AB"));
    printf("%d
",sizeof("S65AB"));
    printf("%d
",sizeof("S65AB"));
    printf("%d
",sizeof("S65AB"));
    printf("%d
",sizeof("S65AB"));
    return 0;
}

output:

5
6
6
7
6
7

http://ideone.com/kw23IV

Can anyone explain this behaviour with character strings?

Using GCC on Debian 7.4

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The size of a string literal is the number of characters in it including the trailing null byte that is added. If there embedded nulls in the string, they are immaterial; they get counted. It is unrelated to strlen() except that if the literal includes no embedded nulls, strlen(s) == sizeof(s) - 1.

printf("%zu
", sizeof("S65AB"));      // 5: '65' is a single character
printf("%zu
", sizeof("S65AB"));        // 6
printf("%zu
", sizeof("S65AB"));    // 6: '65' is a single character
printf("%zu
", sizeof("S65AB"));  // 7: '6' and '5' are single chars
printf("%zu
", sizeof("S65AB"));      // 6: '5' is a single character
printf("%zu
", sizeof("S65AB"));      // 7

Note that '377' is a valid octal constant, equivalent to 'xFF' or 255. You can use them in strings, too. The value '' is only a special case of a more general octal constant.

Note that sizeof() evaluates to a value of type size_t, and the correct formatting type qualifier in C99 and C11 for size_t is z, and since it is unsigned, u is more appropriate than d, hence the "%zu " format that I used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...