gpt4 book ai didi

c - 使用变量中的数组初始化结构

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:53 25 4
gpt4 key购买 nike

我们如何使用数组(使用其变量)初始化结构?

这个版本运行良好:

MyStruct test = {"hello", 2009};

但是这个版本有问题:

char str[] = "hello";
MyStruct test = {str, 2009};

最佳答案

您不能在 C 中分配数组,因此很遗憾,没有办法直接这样做。不过,您可以使用 strcpy 来复制数据。

typedef struct {
char name[20];
int year;
} MyStruct;

int main() {
MyStruct a = { "hello", 2009 }; // works

char s[] = "hello";
MyStruct b = { "", 2009 }; // use dummy value
strcpy(b.name, s);

return 0;
}

关于c - 使用变量中的数组初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767137/

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