首页 > 解决方案 > 为什么我的字符串在初始化时会被连接起来?

问题描述

我正在尝试练习声明字符串,但我没有得到正确的输出。

#include <stdio.h>                   //Im using vscode and gcc
int main()
{
    char k[]= "prac c";
    char l[6]= "stop c";            //first initializing as size 6
    char m[6]= "nice c";

    printf("%s \n%s \n%s",k,l,m);
    return 0;
 }

output: prac c
        stop cprac c
        nice cstop cprac c    

但是当我将大小从 6 更改为 7 时,这不会发生。

#include <stdio.h>
int main()
{
    char k[]= "prac c";
    char l[7]= "stop c";     //changing size to 7
    char m[7]= "nice c";     //changing size to 7

    printf("%s \n%s \n%s",k,l,m);
return 0;
}

output: prac c
        stop c
        nice c 

标签: cstringvariablesprintf

解决方案


该字符串"stop c"实际上是七个字符长,包括结尾的null-terminator。这适用于所有字符串。

如果您的数组中没有用于终止符的空间,则不会添加它,并且数组不再是通常所说的字符串。

使用这样的数组作为字符串将导致代码超出数组的范围并给您未定义的行为


推荐阅读