C 结构字符数组用法
我无法理解这是如何实现的:C 结构字符数组用法,c,char,structure,C,Char,Structure,我无法理解这是如何实现的: struct main_s { char test[1]; }; 是二维阵列测试[1][x]? 例如,如何将字符串“Hello World”传递给结构的字段 字符数组[1][11]={{“H”、“e”、“l”、“l”、“o”、“u”、“W”、“o”、“r”、“l”、“d”} 并且main_s->test=数组不工作,编译器给出了关于类型的错误,1是char[],另一个是char* 如何将字符串“Hello World”传递给结构的字段 您必须首先声明足够的内存
struct main_s {
char test[1];
};
是二维阵列测试[1][x]? 例如,如何将字符串“Hello World”传递给结构的字段 字符数组[1][11]={{“H”、“e”、“l”、“l”、“o”、“u”、“W”、“o”、“r”、“l”、“d”} 并且main_s->test=数组不工作,编译器给出了关于类型的错误,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]);
相当于:
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测试[1]
类似于字符测试代码>
按如下方式更改结构以存储地址
主结构{
字符*测试;
};
现在,下面的代码可以工作了
char array[1][11] = { {"H","e","l","l","o"," ","W","o","r","l","d"} };
struct main_s var;
var->test = array;
您的字符数组是大小为1的数组,因此您只能在其中放入一个字符。如果要将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复制到分配给指针的内存中 您根本不清楚自己在问什么,但这看起来像我们的老朋友struct hack()。参考资料回答了你的问题吗?“这是二维数组测试[1][x]?“什么?!你在哪里看到这两个维度?
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")
}