我正在尝试了解 C 中的嵌套结构和指针。我将此作为测试:
typedef struct xyz xyz_t;
struct xyz{
int x, y, z;
};
xyz_t array[] = {
{.x = 14, .y = 16, .z = 18},
{.x = 34, .y = 36, .z = 38},
{.x = 64, .y = 66, .z = 68},
};
typedef struct blue blue_t;
struct blue
{
int *pointer;
};
int main()
{
blue_t red;
red.pointer = &array;
printf("%d",red.pointer[1].z);
}
这个想法是让结构red
有一个指向array
的指针,然后打印f.ex。数组[1].z
.
我做错了什么?编译器告诉我:
assignment from incompatible pointer type
[-Wincompatible-pointer-types]
red.pointer = &array;
request for member
x
in something not a structure or unionprintf("%d",red.pointer[2].x);
最佳答案
The idea is to have the structure 'red' have a pointer pointing to 'array', and then print f.ex. array[1].z.
在这种情况下,您需要在“蓝色”结构中有一个指向 xyz_t
的指针。
struct blue
{
xyz_t *pointer;
};
您需要从此 red.pointer = &array;
中删除 &
。 array
将被转换为指向 red.pointer = array;
中第一个元素的指针,这是正确的类型(以匹配 LHS)请参阅 What is array decaying? ;而 &array
的类型为 struct xyz (*)[3]
。
此外,您可以为 main 函数使用正确的签名(int main(void)
)。 red
对于 blue_t
类型来说可能是一个令人困惑的变量!
关于c - C 中的结构体与指针和结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142352/