我有这个复杂的结构:
#include <stdlib.h>
typedef struct {
int x;
int y;
} SUB;
typedef struct {
int a;
SUB *z;
} STRUCT;
#define NUM 5
int main(void)
{
STRUCT *example;
int i;
example = malloc(sizeof(STRUCT));
example->z = malloc(NUM * sizeof(SUB));
for(i = 0; i < NUM; ++i) {
/* how do I access variable in certain struct of array of z's */
}
return 0;
}
example
是动态分配的结构,example
中的 z
是动态分配的 SUB
结构数组。
如何访问结构 z
的特定元素中的特定变量?
我一直在尝试这样的事情:example->z[i].x
但它似乎不起作用。
目前我正在使用这个看起来破旧的工作区:
SUB *ptr = example->z;
int i;
for(i = 0; i < amount_of_z_structs; ++i) {
/* do something with 'ptr->x' and 'ptr->y' */
ptr += sizeof(SUB);
}
最佳答案
您的问题不在您所说的地方。您发布的代码给出了编译错误:
error: request for member ‘z’ in something not a structure or union
在线
example.z = malloc(sizeof(STRUCT));
因为您打算编写 example->z
,因为 example
是指向 STRUCT
的指针,而不是 STRUCT
.
从那里开始,您可以完全按照您所说的访问 example->z[i].x
。这种语法一直很好。
例如:
/* your declarations here */
example = malloc(sizeof(STRUCT));
example->z = malloc(NUM * sizeof(SUB));
for(i = 0; i < NUM; ++i) {
example->z[i].x = i;
example->z[i].y = -i;
printf("%d %d\n", example->z[i].x, example->z[i].y);
}
/* output:
0 0
1 -1
2 -2
3 -3
4 -4
*/
关于C和动态结构元素访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520754/