I'm trying to allocate memory to hold an array of structs
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));
}
These are my structs
typedef struct{
int id;
char ip_addr[MAX_IP + 1];
int port;
}SERVER;
typedef struct{
int server1;
int server2;
int weight;
}PATH;
And then later in my code I try to free it using
for (int i = 0; i < 10; ++i)
{
free(paths[i]);
}
free(paths);
for (int i = 0; i < 10; ++i)
{
free(topology[i]);
}
free(topology);
I keep getting the following error
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 *);
I'm generally new to C. Any help appreciated.
Try this:
typedef struct SERVER {
....
} SERVER;
typedef struct PATH {
....
} PATH;
You see, you use struct SERVER
and struct PATH
but you haven't declared these. You did declare a type SERVER
and a type PATH
using a typedef
on an unnamed struct.
Alternatively, you could leave your structs as they are, and use sizeof(PATH*)
and sizeof(STRUCT*)
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments