c - 二维字符数组

标签 c output

#include<stdio.h>

void main()
{
    char a[10][5] = {"hi", "hello", "fellow"};
    printf("%s",a[0]);
}

为什么这个代码只打印 你好

#include<stdio.h>

void main()
{
    char a[10][5] = {"hi", "hello", "fellow"};
    printf("%s",a[1]);
}

虽然此代码正在打印“hellofellow

最佳答案

Why this code printing only hi

您已经告诉 printf 打印存储在 a[0] 的字符串,而该字符串恰好是 "hi"

While this code is printing "hellofellow"

这是巧合,事实上你的代码应该被编译器拒绝,原因是 a constraint violation :

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

字符串 "fellow",特别是它末尾的 'w' 不适合 char[5]初始化,这违反了 C 标准。也许也是巧合,您的编译器提供了一个扩展(从技术上讲它是一个非 C 编译器),所以您看不到 the error messages我做的:

prog.c:3:6: error: return type of 'main' is not 'int' [-Werror=main]
 void main()
      ^
prog.c: In function 'main':
prog.c:5:37: error: initializer-string for array of chars is too long [-Werror]
     char a[10][5] = {"hi", "hello", "fellow"};
                                     ^

请注意,第二条错误消息是提示 "fellow",而不是 "hello"。你的 "hello" 初始化 is valid by exception :

An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

重点是我的。强调的部分指出,如果没有足够的空间容纳终端 '\0' 字符,则不会在初始化中使用该字符。

关于c - 二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932921/

相关文章:

php - 在基于 C 的 Web 服务器上执行和输出 PHP - 卡住了!

c - 分别存储数组每个子集的总和,而不是所有子集的总和

c - 多线程导致 C 语言性能下降

c - 如何从文件读取两个字符串并将它们存储在两个单独的数组中

c - 与数组访问混淆

MongoDB聚合查询

c - 如何进行 "superlong"整数的乘法和除法?

c - 在 C 中打印并插入静态矩阵

database - 数据库;查询输出,强制表输出?

java - 中断 shell 输出到文件