gpt4 book ai didi

c - 我得到 "Invalid Initializer",我做错了什么?

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

int main(void) {
char testStr[50] = "Hello, world!";
char revS[50] = testStr;
}

我收到错误:revS 行上的“无效初始值设定项”。我做错了什么?

最佳答案

您不能以这种方式初始化 revS,您需要在 = 的右边有一个非常具体的东西。来自 C11 6.7.9 初始化/14、/16:

14/ 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.

: : :

16/ Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed list of initializers for the elements or named members.


要获得相同的结果,您可以将代码替换为:

int main (void) {
char testStr[50] = "Hello, world!";
char revS[50]; strcpy (revS, testStr);
// more code here
}

从技术上讲,这不是初始化,但实现了相同的功能结果。如果你真的想要初始化,你可以使用类似的东西:

#define HWSTR "Hello, world!"
int main (void) {
char testStr[50] = HWSTR;
char revS[50] = HWSTR;
// more code here
}

关于c - 我得到 "Invalid Initializer",我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043313/

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