我想要做的只是初始化一个struct的实例。结构在这里定义:
typedef struct Rectangle
{
tName Name; /* name of the rectangle */
struct Rectangle * binSon[2];
int Center[2];
int Length[2]; /* distance to the boarder of the rectangle */
int Label;
}Rectangle;
以及我如何初始化它如下所示:
Rectangle * binSon[2];
binSon[0] = NULL;
binSon[1] = NULL;
int Center[2];
int Length[2];
Center[0] = 0;
Center[1] = 0;
Length[0] = 5;
Length[1] = 5;
Rectangle world = {"World", binSon, Center, Length, 0};
在最后一行,当我编译程序时,它向我报警:
mx_cif_ds_manager.c:52:2: warning: initialization makes integer from pointer without a cast [enabled by default]
mx_cif_ds_manager.c:52:2: warning: (near initialization for 'world.Name[0]') [enabled by default]
mx_cif_ds_manager.c:52:2: warning: initialization makes integer from pointer without a cast [enabled by default]
mx_cif_ds_manager.c:52:2: warning: (near initialization for 'world.Name[1]') [enabled by default]
mx_cif_ds_manager.c:52:2: warning: initialization makes integer from pointer without a cast [enabled by default]
mx_cif_ds_manager.c:52:2: warning: (near initialization for 'world.Name[2]') [enabled by default]
mx_cif_ds_manager.c:52:2: warning: initialization makes integer from pointer without a cast [enabled by default]
mx_cif_ds_manager.c:52:2: warning: (near initialization for 'world.Name[3]') [enabled by default]
不确定这个程序出了什么问题,并想知道是否有任何人有任何想法或建议可以帮助我改进这段代码。什么是初始化结构的更基础的方法?
谢谢
====== UPDATE ==
感谢您的帮助,但是如果我想使用变量初始化结构怎么办?在这种情况下,我是否必须对内存空间进行malloc?
tName定义在这里
typedef char tName[MAX_NAME_LEN + 1];
答案 0 :(得分:15)
这应该有效:
Rectangle world = {"World", {NULL, NULL}, {0, 0}, {5, 5}, 0};
答案 1 :(得分:4)
更简单:
Rectangle world = { "World", { NULL, NULL }, { 0, 0 }, { 5, 5 }, 0 };
答案 2 :(得分:1)
要扩展Keith的答案,您也可以根据需要使用变量。请注意,这仅在您在函数内时才有效。
void foo(void)
{
Rectangle world = {"World", {binSon[0], binSon[1]}, {Center[0], Center[1]}, {Length[0], Length[1]}, 0};
}