[英]Structure with pointer and array of structures in C
I'm trying to learn about nested structures and pointers in C. I made this as a test: 我试图学习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);
}
The idea is to have the structure red
have a pointer pointing to array
, and then print f.ex. array[1].z
想法是让red
结构体具有指向array
的指针,然后print f.ex. array[1].z
print f.ex. array[1].z
. print f.ex. array[1].z
。
What am I doing wrong? 我究竟做错了什么? The compiler is telling me: 编译器告诉我:
assignment from incompatible pointer type 从不兼容的指针类型分配
[-Wincompatible-pointer-types]
red.pointer = &array;
[-Wincompatible-pointer-types]red.pointer = &array;
request for member
x
in something not a structure or unionprintf("%d",red.pointer[2].x);
请求成员x
使用非结构或联合printf("%d",red.pointer[2].x);
The idea is to have the structure 'red' have a pointer pointing to 'array', and then print f.ex. 想法是使结构“ red”具有指向“ array”的指针,然后打印f.ex。 array[1].z. 阵列[1] .Z。
In that case, you need to have a pointer to xyz_t
in your "blue" struct. 在这种情况下,您需要在“蓝色”结构中有一个指向xyz_t
的指针。
struct blue
{
xyz_t *pointer;
};
You need to drop the &
from this red.pointer = &array;
您需要删除&
此red.pointer = &array;
. 。 array
will be converted into a pointer to its first element in red.pointer = array;
array
将被转换为指向red.pointer = array;
第一个元素的指针red.pointer = array;
which is the correct type (to match LHS) See What is array decaying? 哪种是正确的类型(以匹配LHS),请参阅什么是数组衰减? ; ; whereas &array
is of type struct xyz (*)[3]
. 而&array
的类型为struct xyz (*)[3]
。
Aside, you could use a proper signature for main function ( int main(void)
). 另外,您可以为main函数使用适当的签名( int main(void)
)。 red
could be a confusing a variable for a blue_t
type! red
可能是blue_t
类型的令人困惑的变量!
This should be fixed. 这应该是固定的。 See if it helps: 看看是否有帮助:
typedef struct xyz{
int x, y, z;
} xyz_t;
xyz_t array[] = {
{.x = 14, .y = 16, .z = 18},
{.x = 34, .y = 36, .z = 38},
{.x = 64, .y = 66, .z = 68},
};
typedef struct {
xyz_t *pointer;
} blue_t;
int main()
{
blue_t red;
red.pointer = &array;
printf("%d",red.pointer[1].z);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.