gpt4 book ai didi

c - 包含字符串的结构体的初始化

转载 作者:行者123 更新时间:2023-11-30 18:42:04 25 4
gpt4 key购买 nike

在下面的程序中,第 5 行给出了错误,但第 11 行没有给出错误,而两者都在做相同的事情,即用 0 初始化字符串?我非常清楚它会给出编译器错误。我的疑问是,如果第 5 行给出了错误,那么为什么第 11 行没有给出错误?

#include<stdio.h>
int main()
{
char name[20]=0; //This should also run if line 11 runs without an error where string is being initialized by zero.
struct node
{
char name[20];
int no;
};
struct node a={0};
}

最佳答案

如果要初始化复合对象(数组、结构、 union ),则需要将值放在大括号 {} 内。所以你需要写

char name[20] = { 0 };  /* Or '\0' */

字符串是一种特殊情况,编译器会处理它,因此您可以编写例如:

char name[20] = "";

关于c - 包含字符串的结构体的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18506239/

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