gpt4 book ai didi

c - 结构体char数组的使用

转载 作者:行者123 更新时间:2023-11-30 19:22:25 24 4
gpt4 key购买 nike

我无法理解这是如何实现的:

struct main_s {
char test[1];
};

它是一个二维数组 test[1][x] 吗?例如如何将字符串“Hello World”传递到结构体的字段?

字符数组[1][11] = { {"H","e","l","l","o","","W","o","r","l","d"} };

并且 main_s->test = array 不起作用,编译器给出有关类型的错误,1 是 char [],另一个是 char*。

最佳答案

how to pass a string "Hello World" to the field of the structure ?

您首先必须为 test 数组声明足够的内存空间来包含所需的字符串。 “Hello World” 包含 11 个字符。所以你的数组应该至少包含 12 个元素

struct main_s {
char test[12];
};

然后将字符串复制到数组中:

struct main_s m;
strcpy(m.test, "Hello World");
printf("%s\n", m.test) // this display the content of your char array as string

如果你想声明一个二维数组:

struct main_s {
char test[3][13];
}

struct main_s m;
strcpy(m.test[0], "Hello World0");
strcpy(m.test[1], "Hello World1");
strcpy(m.test[2], "Hello World2");
printf("%s\n%s\n%s\n", m.test[0], m.test[1], m.test[2]);

strcpy(m.test[1], "Hello World1");

相当于:

m.test[1][0]='H';
m.test[1][1]='e';
m.test[1][2]='l';
.
.
m.test[1][10]='d';
m.test[1][11]='1';
m.test[1][12]='\0'; //add null charachter at the end. it's mandatory for strings

以上代码不允许

m.test[1] = "Hello World1";
m.test[1] = {'H','e','l','l','o',' ','W','o','r','l','d','1'};

关于c - 结构体char数组的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16527306/

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