2

I wrote this function that creates new nodes.

When I add only one node, the program works but if I add the second node I get a segmentation fault, so clearly the problem lies in the "else" part of the function "add_node()" but I can't figure it out.

#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;
    }
}
4

3 回答 3

3

您有一个循环运行,直到current为 NULL ... 然后您设置current->nexty,但current必须为 NULL。

解决它的一个简单方法是将循环更改为

while (current->next != NULL){

我还要注意,您应该避免使用全局变量。current应该是一个局部变量,start应该是一个参数......我会称之为它list,因为这就是它所代表的。add_node应该返回 的(可能是新的)值list

于 2013-03-26T18:51:18.443 回答
2

这里:

    while (current != NULL) {
        current = current->next;
    }

    current->next = y;

什么时候while停止?当current成为null. 然后current->next引发分段错误。

你必须停止一个短的NULL。与 相比current->nextNULL而不是current,所以当循环退出时,您仍然指向一个节点。

于 2013-03-26T18:51:53.700 回答
0

这个循环:

while (current != NULL){
    current = current->next;
}

将通过电流直到current == NULL。一旦发生这种情况:

 current->next = y;

将尝试尊重该 NULL,这当然会导致段错误。你只是想要:

while(!current && current->next != NULL)

从技术上讲,您只需要while(current->next != NULL),因为您检查了start,但是 IMO 在您尊重它之前检查指针是否为 NULL 是一种很好的做法。

于 2013-03-26T18:53:22.587 回答