gpt4 book ai didi

c - 分配内存以保存 C 中的结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:18 25 4
gpt4 key购买 nike

我正在尝试分配内存来保存结构数组

SERVER* topology = malloc(sizeof(struct SERVER*)* 10 );
for (int i = 0; i < 10; ++i)
{
topology[i] = malloc(sizeof(struct SERVER));
}
PATH* paths = malloc(sizeof(struct PATH*)*10);
for (int i = 0; i < 10; ++i)
{
paths[i] = malloc(sizeof(struct PATH));
}

这些是我的结构

typedef struct{
int id;
char ip_addr[MAX_IP + 1];
int port;
}SERVER;

typedef struct{
int server1;
int server2;
int weight;
}PATH;

然后在我的代码中,我尝试使用

释放它
for (int i = 0; i < 10; ++i)
{
free(paths[i]);
}
free(paths);

for (int i = 0; i < 10; ++i)
{
free(topology[i]);
}
free(topology);

我不断收到以下错误

error: invalid application of 'sizeof' to an incomplete type 'struct SERVER'
topology[i] = malloc(sizeof(struct SERVER));
^ ~~~~~~~~~~~~~~~
:18:42: note: forward declaration of 'struct SERVER'
SERVER* topology = malloc(sizeof(struct SERVER*)* 10 );
^
:26:21: error: invalid application of 'sizeof' to an incomplete type 'struct PATH'
paths[i] = malloc(sizeof(struct PATH));
^ ~~~~~~~~~~~~~
:23:37: note: forward declaration of 'struct PATH'
PATH* paths = malloc(sizeof(struct PATH*)*10);

......

c:97:11: error: passing 'PATH' to parameter of incompatible type 'void *'
free(paths[i]);
^~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/stdlib.h:143:18: note: passing argument to parameter here
void free(void *);
^
:103:11: error: passing 'SERVER' to parameter of incompatible type 'void *'
free(topology[i]);
^~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/stdlib.h:143:18: note: passing argument to parameter here
void free(void *);

我通常是 C 的新手。感谢任何帮助。

最佳答案

试试这个:

typedef struct SERVER {
....
} SERVER;

typedef struct PATH {
....
} PATH;

你看,你使用了 struct SERVERstruct PATH 但你还没有声明它们。您确实在未命名的结构上使用 typedef 声明了类型 SERVER 和类型 PATH

或者,您可以保持结构不变,并使用 sizeof(PATH*)sizeof(STRUCT*)

关于c - 分配内存以保存 C 中的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33710343/

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