数组中的C结构 [英] Array in C struct
本文介绍了数组中的C结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想有一个结构两个阵列,这是在启动初始化,但还需要进一步的编辑。我需要的结构的三个实例,这样我可以索引到一个特定的结构和修改如我所愿。这可能吗?
这是我想我可以做的,但我得到的错误:
结构potNumber {
int数组[20] = {[0 ... 19] = 10};
字符* theName [] = {一半对一半,杏仁,树莓,香草,...};
} APOT [3];
然后我访问结构如下:
的printf(一些语句%S,APOT [0] .array [0]);
APOT [0] .theName [3];
...
解决方案
该结构本身没有数据。您需要创建的结构类型的对象和设置的对象...
结构potNumber {
int数组[20];
字符* theName [42];
};/ *我喜欢从对象创建的类型定义分离* /
结构potNumber APOT [3];
/ *用C99编译器,你可以使用指定的初始值'* /
结构potNumber bPot = {{[7] = 7,[3] = -12},{[4] =四,[6] =六}};对于(I = 0; I&小于20;我++){
APOT [0] .array [我] =我;
}
APOT [0] .theName [0] =一半对一半;
APOT [0] .theName [1] =杏仁;
APOT [0] .theName [2] =树莓;
APOT [0] .theName [3] =香草;
/ * ... * /对于(I = 0; I&小于20;我++){
APOT [2] .array [I] = 42 + I;
}
APOT [2] .theName [0] =一半对一半;
APOT [2] .theName [1] =杏仁;
APOT [2] .theName [2] =树莓;
APOT [2] .theName [3] =香草;
/ * ... * /
I want to have two arrays in a struct, which are initialized at start but need editing further on. I need three instances of the struct, so that I can index into a specific struct and modify as I wish. Is it possible?
This is what I thought I could do but I get errors:
struct potNumber{
int array[20] = {[0 ... 19] = 10};
char *theName[] = {"Half-and-Half", "Almond", "Rasberry", "Vanilla", …};
} aPot[3];
Then I access the structs as follows:
printf("some statement %s", aPot[0].array[0]);
aPot[0].theName[3];
…
解决方案
The struct themselves do not have data. You need to create objects of the struct type and set the objects ...
struct potNumber {
int array[20];
char *theName[42];
};
/* I like to separate the type definition from the object creation */
struct potNumber aPot[3];
/* with a C99 compiler you can use 'designated initializers' */
struct potNumber bPot = {{[7] = 7, [3] = -12}, {[4] = "four", [6] = "six"}};
for (i = 0; i < 20; i++) {
aPot[0].array[i] = i;
}
aPot[0].theName[0] = "Half-and-Half";
aPot[0].theName[1] = "Almond";
aPot[0].theName[2] = "Rasberry";
aPot[0].theName[3] = "Vanilla";
/* ... */
for (i = 0; i < 20; i++) {
aPot[2].array[i] = 42 + i;
}
aPot[2].theName[0] = "Half-and-Half";
aPot[2].theName[1] = "Almond";
aPot[2].theName[2] = "Rasberry";
aPot[2].theName[3] = "Vanilla";
/* ... */
这篇关于数组中的C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文