【发布时间】:2014-03-18 15:36:41
【问题描述】:
你好,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct data{
int a;
struct data *p;
}data;
void add(data *begin, data *new);
int main(void){
data *first = malloc(sizeof(data));
data *second = malloc(sizeof(data));
data *third = malloc(sizeof(data));
first->a = 1;
first->p = second;
second->a = 2;
second->p = third;
third->a = 3;
third->p = NULL;
data *new = malloc(sizeof(data));
new->a = 4;
add(first, new);
data *temp = first;
do{
printf("%i\n", temp->a);
temp = temp->p;
}
while(temp->p != NULL);
return 0;
}
void add(data *begin, data *new){
data *temp = malloc(sizeof(data));
temp = begin;
while(1){
if(temp->p == NULL){
temp->p = new;
break;
}
else{
temp = temp->p;
}
}
}
代码很简单。但是当我运行它时,我总是得到 3 (它不会添加新列表)。请帮助我,我找不到类似的问题,可以帮助我。
【问题讨论】:
-
我希望你在 c 工作;在 c++ 中,“new”是保留关键字;这不是一个明智的命名选择......
-
是的,我正在使用 C,检查我包含的库(stdio 和 stdlib)。
-
new 在 oldschool c 中也不是明智的命名选择,恕我直言。另外,你能解释一下为什么你在 add 中使用 malloc 吗?
标签: c struct linked-list