【问题标题】:Why are my strings getting concatenated as I initialize them? [duplicate]为什么我的字符串在初始化时会被连接起来? [复制]
【发布时间】:2021-12-17 14:11:03
【问题描述】:

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

#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 

【问题讨论】:

  • 开头还有这个奇怪的空格,你在printf打印一个空格。此外,lm 的大小必须为 7 而不是 6 - NULL ('\0') 终止符要多出一个字符。
  • @kiner_shah 感谢它的工作,我刚刚意识到字符串的大小将是一个额外的。

标签: c string variables printf


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    "prac c", "stop c", "nice c" 分别占用 7 个字节,因为字符串文字有一个终止 \0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2016-06-13
      • 2013-10-04
      • 2015-07-31
      • 1970-01-01
      • 2021-03-09
      • 2023-03-29
      相关资源
      最近更新 更多