C和动态结构元素访问

标签 c pointers struct element structure

我有这个复杂的结构:

#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/

相关文章:

c - C 中的数字螺旋,代码不起作用

c - 是否可以确定 pthread_t 结构是否未使用?

c - c编程中使用openssl使用文件IO进行三重DES加密解密

ios - 如何为自定义结构编写类似于 CGRectZero 的宏

python - 将调用 C 函数的 Python 2.7 代码移植到 Python 3.4

c++ - 关于类内部指针的问题

c++ - 指向存储在 uint64_t 中的内存位置的指针

go - 在 Go 中附加到结构 slice

c# - Vector3非 float ?

在 C 中传递和修改 char 指针之间的混淆(引用与值)