我很难理解这是如何工作的:
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*。
如何将字符串“Hello World”传递给结构的字段?
您必须首先为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'};
您不能将字符串传递"Hello world"
给该数组。它是单个 char 变量。
char test[1];
类似于char test;
。
改变结构如下存储地址,
结构 main_s { char *test; };
现在下面的代码将起作用。
char array[1][11] = { {"H","e","l","l","o"," ","W","o","r","l","d"} };
struct main_s var;
var->test = array;
您的 char 数组是一个大小为 1 的数组,因此您只能在其中放置一个 char。如果你想将 Hello World 传递给这个结构,它会是这样的:
struct main_s{
char * test;
};
int main(){
struct main_s a;
a.test = malloc(sizeof(n)) //Where n is the size you want so how ever many chars hello world is followed by null
memcpy(a, "Hello World\0")
}
这基本上是它的工作原理。您需要将 Hello World\0 复制到分配给 hte 指针的内存中。