I think this question got answered in many ways now, but I am still confused and I am doing strange things with the pointers, so I would really appreciate your help. I want to create an array (unknown size) which contains linked lists. I think the main problems are my use of pointers in this context. Please take a look:
int x_format;
int y_format;
typedef struct{
int id;
struct item_node *next;
union{
struct{
int freq
} Sound;
struct{
float reduce;
} Obstacle;
} data;
}item_node;
item_node *buffer;
item_node **room;
item_node **room_new;
void createRoom(int x, int y)
{
buffer = malloc(sizeof(item_node)*x*y);
room = malloc(sizeof(item_node *)*y);
for(int i = 0; i<y; i++)
room[i] = &buffer[i*x];
for(int j = 0; j<x; ++j)
{
for(int k = 0; k<y; ++k)
{
room[j][k].next = NULL;
}
}
}
item_node createItem (int x, int y, int id)
{
item_node selected = room[x][y];
//Error
if(selected == NULL)
selected = malloc(sizeof(item_node));
else{
while(selected->next != NULL)
selected = selected->next;
selected->next = malloc(sizeof(item_node));
selected = selected->next;
}
selected->id = id;
selected->next = NULL;
return selected;
}
int main (int argc, char *argv[])
{
x_format = 100;
y_format = 100;
createRoom(x_format,y_format);
item_node itemtest = createItem(1,1,0);
free(room);
free(buffer);
}
So the problem that occurs is:
error: invalid operands to binary expression ('item_node' and 'void *') if(selected == NULL)
I understand the error but I don't now how to fix that. Sorry if this question is way to trivial and I appreciate any help! Thank you.
On topic, the problem is right here:
item_node createItem (int x, int y, int id){
item_node selected = room[x][y];
//Error
if(selected == NULL)
selected = malloc(sizeof(item_node));
In your case item_node selected is a variable, not a pointer. You declared selected to be a variable of item_node, which is a struct. No pointers here. Then you are comparing a variable of a certain type with NULL (which is defined as (void*) 0 in plain C).
Off topic: The entire program seems flawed at first sight, though. Please revise the algorithm and the data structures, it seems to me you're blending pointers and array a little to freely.
I'm pretty sure that your item_node data type is not a pointer, but a structure. However in the highlighted line you compare an exemplar of such structure to void pointer (and do other stuff later on), which is a mistake. Apparently, the following was intended:
1) item_node* createItem (int x, int y, int id)
2) item_node* selected = room[x][y];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.