【发布时间】:2013-03-26 18:49:05
【问题描述】:
我编写了这个创建新节点的函数。
当我只添加一个节点时,程序可以工作,但是如果我添加第二个节点,我会遇到分段错误,所以很明显问题出在函数“add_node()”的“else”部分,但我不能想办法。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
char *city;
struct node *next;
}node;
node *start = NULL;
node *current;
void add_node(char *cityname) {
node *y = malloc(sizeof(node));
y->city = cityname;
y->next = NULL;
current = start;
if(start == NULL) {
start = y;
} else {
while (current != NULL) {
current = current->next;
}
current->next = y;
}
}
int main() {
add_node("Paris");
add_node("London");
current = start;
while(current != NULL) {
printf("%s\n", current->city);
current = current->next;
}
}
【问题讨论】:
标签: c