简体   繁体   中英

Why is the number '7' printed after my string in C?

I need to define the characters in an array and print the string...But it always prints as string7 (in this case, test7)...What am I doing wrong here?

#include <stdio.h>
int main() {
    char a[]={'t','e','s','t'};
    printf("%s\n",a);
    return 0;
}

Why this behavior?

Because you did not \\0 terminate your array, so what you get is Undefined behavior .

What possibly happens behind the scenes ?

The printf tries to print the string till it encounters a \\0 and in your case the string was never \\0 terminated so it prints randomly till it encounters a \\0 .
Note that reading beyond the bounds of allocated memory is Undefined behavior so technically this is a UB.

What you need to do to solve the problem?

You need:

char a[]={'t','e','s','t',`\0`};

or

char a[]="test";

Because your "string", or char[] , is not null-terminated (ie terminated by \\0 ).

then, printf("%s", a); will attempt to print every character starting from the start of a and keep printing until it sees until it sees a \\0 .

That \\0 is outside your array, and depends on the initial state of the memory of your program, which you pretty much don't have control.

to fix this, use

char a[]={'t','e','s','t','\0'};

您打印的字符串必须以null结尾...所以您的字符串声明应该是,

char a[]={'t','e','s','t', '\0'};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM