插入新节点 [英] Inserting New Node
问题描述
这是我正在写的一个程序的功能,可以更熟悉节点.
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;
不幸的是,它给了我new_node-> location = code不兼容的类型;
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;
}
推荐答案
LibraryCode
被 typdef
用作 char [4]
.您不能只将一个数组分配给另一个数组,而是需要将 memcpy
或 strcpy
数据从一个数组分配到另一个数组.
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.
一个简单的例子:
void foo() {
char a[4];
char b[4];
a = b;
}
编译此错误:
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.
typedef char LibraryCode [4];
可能不是一个好主意.如果您要在节点中为字符串保留一个固定大小的缓冲区,那么我将放弃 typedef
,这样您就可以清楚地知道自己在做什么.另外,我绝不会将 char [4]
按值传递给函数.对于字符串,请传递 const char *
.
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*
.
这篇关于插入新节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!