gpt4 book ai didi

c - 二维字符数组

转载 作者:太空狗 更新时间:2023-10-29 15:54:29 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com