gpt4 book ai didi

c - 在 C 中初始化一个结构

转载 作者:行者123 更新时间:2023-12-02 05:24:41 24 4
gpt4 key购买 nike

我想做的只是初始化一个结构的实例。该结构在这里定义:

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]

不确定这段程序出了什么问题,想知道是否有人有任何想法或建议可以帮助我改进这段代码。什么是初始化结构的更温和的方法?

谢谢

======更新======

感谢您的帮助,但是如果我想使用变量来初始化结构体怎么办。在这种情况下,我是否必须 malloc 内存空间?

tName 定义在这里

typedef char tName[MAX_NAME_LEN + 1];

最佳答案

这应该有效:

Rectangle world = {"World", {NULL, NULL}, {0, 0}, {5, 5}, 0};

关于c - 在 C 中初始化一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12587666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com