开发者

char Array problem in C

char label[8] = "abcdefgh";
char 开发者_高级运维arr[7] = "abcdefg";

printf("%s\n",label);
printf("%s",arr);

====output==========

abcdefgh

abcdefgÅ

Why Å is appended at the end of the string arr? I am running C code in Turbo C ++.


printf expects NUL-terminated strings. Increase the size of your char arrays by one to make space for the terminating NUL character (it is added automatically by the = "..." initializer).

If you don't NUL-terminate your strings, printf will keep reading until it finds a NUL character, so you will get a more or less random result.


Your variables label and arr are not strings. They are arrays of characters.

To be strings (and for you to be able to pass them to functions declared in <string.h>) they need a NUL terminator in the space reserved for them.

Definition of "string" from the Standard

    7.1.1 Definitions of terms
1   A string is a contiguous sequence of characters terminated by and including
    the first null character. The term multibyte string is sometimes used
    instead to emphasize special processing given to multibyte characters
    contained in the string or to avoid confusion with a wide string. A pointer
    to a string is a pointer to its initial (lowest addressed) character. The
    length of a string is the number of bytes preceding the null character and
    the value of a string is the sequence of the values of the contained
    characters, in order.


Your string is not null terminated, so printf is running into junk data. You need to use the '\0' at the end of the string.


Using GCC (on Linux), it prints more garbage:

abcdefgh°ÃÕÄÕ¿UTÞÄÕ¿UTÞ·
abcdefgabcdefgh°ÃÕÄÕ¿UTÞÄÕ¿UTÞ·

This is because, you are printing two character arrays as strings (using %s).

This works fine:

char label[9] = "abcdefgh\0"; char arr[8] = "abcdefg\0";

printf("%s\n",label); printf("%s",arr);

However, you need not mention the "\0" explicitly. Just make sure the array size is large enough, i.e 1 more than the number of characters in your strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜