[英]Allocating memory to hold an array of structs in C
我正在嘗試分配內存以容納結構數組
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 SERVER
和struct PATH
但尚未聲明它們。 您確實在未命名的結構上使用typedef
聲明了SERVER
類型和PATH
類型。
或者,您可以保留結構,並使用sizeof(PATH*)
和sizeof(STRUCT*)
。
這里有幾個問題:
SERVER* topology = malloc(sizeof(struct SERVER*)* 10 );
...
PATH* paths = malloc(sizeof(struct PATH*)*10);
SERVER
的類型,它是匿名結構的typedef。 您尚未定義struct SERVER
,因此請使用SERVER
而不是struct SERVER
。 PATH
。 SERVER
指針分配空間,但是topology
是指向SERVER
的指針,這意味着它可以充當SERVER
的數組,而不是SERVER *
的數組,這就是您的使用方式。 這就是為什么在調用free
時出現錯誤的原因,因為topology[i]
是一個SERVER
,而不是SERVER *
。 PATH
也是如此。 為了使此方法正常運行,您需要按以下方式定義topology
和paths
:
SERVER **topology = malloc(sizeof(SERVER *) * 10 );
PATH **paths = malloc(sizeof(PATH *) * 10);
或者,您可以保留當前定義並立即分配整個數組,而不是先分配一個指針數組,然后再分配單個元素:
SERVER *topology = malloc(sizeof(SERVER) * 10);
PATH *paths = malloc(sizeof(PATH) * 10);
然后像這樣清理:
free(topology);
free(paths);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.