问题
Here is a function of a program I'm writing to get more familiar with nodes.
It creates a new node and inserts the information into the code field and then points to the existing first node. Then assigns the head to the newly created node;
Unfortunately it's giving me a incompatible types for new_node->location = code;
typedef char LibraryCode[4];
typedef struct node {
LibraryCode location;
struct node *next;
} Node;
void insertFirstNode(LibraryCode code, Node **listPtr) {
Node *new_node;
new_node=malloc(sizeof(Node));
new_node->location = code;
new_node->next = *listPtr;
*listPtr = new_node;
}
回答1:
LibraryCode
is typdef
ed as a char [4]
. You can't just assign one array to another, you'll need to memcpy
or strcpy
the data from one array to the other.
A simpler example of what's going on:
void foo() {
char a[4];
char b[4];
a = b;
}
Compiling this gives the error:
In function ‘foo’:
error: incompatible types when assigning to type ‘char[4]’ from type ‘char *’
a = b;
^
You can see that you're actually trying to assign a pointer to the array, which are incompatible types.
The typedef char LibraryCode[4];
is probably not a good idea anyway. If you're going to keep a fixed-size buffer for the string in your node, then I would just ditch the typedef
so it's clear what you're doing. Also, I would never pass a char [4]
by value to a function. For strings, pass a const char*
.
来源:https://stackoverflow.com/questions/22216607/inserting-new-node