【发布时间】:2019-02-13 16:49:14
【问题描述】:
这是我的代码(处理链表):
typedef struct node {
int data;
struct node_t* next;
} node_t;
typedef struct list{
node_t* head;
} list_t;
node_t* create_node(void){
node_t* tmp = malloc(sizeof(node_t));
if (tmp == NULL){
fprintf(stderr, "Error while allocating memory for node\n");
exit(EXIT_FAILURE);
}
return tmp;
}
void list_insert(list_t* list, node_t* node, int data){
if (node == NULL){
node_t* new = create_node();
new->next = list->head;
list->head = new;
new->data = data;
}
else{
node_t* current = list->head;
while(current != node){
current = current->next;
}
node_t* new = create_node();
new->next = current->next;
current->next = new;
new->data = data;
}
}
我确实在 list_insert 函数中收到了一些警告,但我无法弄清楚它们的原因。如果作为参数传递的node 是NULL,则该函数应该在开头插入一个新节点,否则它应该在作为参数传递的node 之后插入一个新节点。
在这个sn-p中:
if (node == NULL){
node_t* new = create_node();
new->next = list->head;
list->head = new;
new->data = data;
}
分配new->next = list->head; 不正确。有什么猜测吗?
【问题讨论】:
-
如果您收到警告,请先解决这些问题。如果您需要这方面的帮助,请在您的问题中说明您收到了哪些警告。
-
在列表中查找
node的循环也应该处理到达列表末尾但没有找到node的情况。 -
这是多次重复,但与以往一样,困难在于找到正确的副本。我不确定是否有规范的问答。 Typdefs, tagged and untagged structures, and incompatible pointer types 密切相关,但并不完全相同(处理标签的存在/不存在,而不是直接处理拼写错误的标签导致混淆)。
-
如果您有兴趣,我将您的程序的更正/修改版本,并附上执行示例
-
Enable Compiler Warnings,对于 gcc/clang,最小
-Wall -Wextra -pedantic,对于 VS/W3,并且在编译没有警告之前不要接受代码。 (只要遵循这条规则,你就会为自己节省无数时间)让你的编译器帮助你编写更好的代码。编译器会告诉你有问题的代码的确切行(通常是确切的起始字符)。永远不要忽视警告。
标签: c