C字符无缘无故地加起来

Quo*_*ane 2 c printf char

我想我快要疯了,因为我找不到C为什么结合我的字符的解释。

我已经给你们做了一个测试程序...

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char alphabet_big[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char alphabet_small[26] = "abcdefghijklmnopqrstuvwxyz";

    printf("%s\n", alphabet_small);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZV

为什么C会结合使用Alphabet_small和Alphabet_big?那没有道理。为什么在字符的末尾有一个“ V”?

我希望有人可以为我提供这个“问题”的答案。

最好的祝福。

ryy*_*ker 5

请记住,C字符串定义为以null结尾的 char数组。

在此处更改声明和初始化语句:(对于两个语句。)

char alphabet_big[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//forces compiler to use only 26 char
                                                     //regardless of the count of initializers
                                                     //(leaving no room for NULL terminator)
Run Code Online (Sandbox Code Playgroud)

char alphabet_big[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//allows compiler to set aside
                 ^^                                 //the proper space, no matter how many initializers
Run Code Online (Sandbox Code Playgroud)

The first produces undefined behavior when using with any of the string functions, such as strcpy, strcmp, and in this case printf with the "%s" format specifier.

The first produces the following, which is not is not a C string:

|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|?|?|?|     
Run Code Online (Sandbox Code Playgroud)

While the 2nd produces the following, which is a C string:

|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|\0|?|?|   
Run Code Online (Sandbox Code Playgroud)

Note - The ? symbols used in above illustration depict memory locations that are not owned by the program, and for which the contents are unknown, or may not even exist. A program attempting to access these locations would be invoking undefined behavior.