c - C中的指针问题

标签 c pointers struct linked-list

我的 C 指针和结构有问题(我知道,我知道,非常基础!)。我正在练习我的程序范式。这是我第一次使用调试器,因为在我生命的早期我并没有真正需要它:<所以如果你能帮助我,我将不胜感激。

我定义了以下结构来制作列表:

typedef struct node {
    int info;
    struct node *next;
    struct node *prev;
} node_t;

然后这个函数来填充它:

void addNodo(node_t * list, int x){
    node_t * pointer;
    node_t * temp;

    temp = (node_t *)malloc(sizeof(node_t));
    temp->info = x;
    temp->next = NULL;
    temp->prev = NULL;

    pointer = list;

    if(pointer == NULL){ //it's empty so start it
        list = temp;
        return;
    }

    if (pointer->info <= x) { //I like my lists tidy so...
        while((pointer->next != NULL) && (pointer->info <= x)){
            pointer = pointer->next;
        }

        if(pointer->next == NULL){
            pointer->next = temp;
            temp->prev = pointer;
            return;
        }

        pointer->next->prev = temp;
        temp->next = pointer->next;
        temp->prev = pointer;
        pointer->next = temp;
        return;
    }
}

然后,这样做:

int main(int argc, char** argv) {
    node_t * list = NULL;
    addNodo(list, 1);
    printf("x: %d", list->info);
    return (EXIT_SUCCESS);
}

它向我抛出一个段错误!当我调试它时,一切都很有趣和游戏,直到它通过++++ 行,列表地址返回到 0x0 并且无法让它工作。我知道某处有错误,但据我对指针的了解,这完全没问题。请检测我的错误并教我一些指示。

最佳答案

当您调用 addNode() 时,您将按值 传递指针。因此,当您在函数体中更改它时,更改将丢失并且不会传播到函数外部。您需要将其声明为:

void addNode(node_t **pointer, int x)

然后在函数中使用*pointer

并且当你在main中调用ity时,传入&list

关于c - C中的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724278/

上一篇:C 中的 CLI 参数

下一篇:c - 基本组装题

相关文章:

c - scanf() 在文件处理中不起作用?

将数组转换为 int/float

c - 为什么我的编译器不接受 fork(),尽管我包含了 <unistd.h>?

c - 函数隐式声明 'BN_init'错误

C++如何使用指针将 vector 的值相乘?

c++ - 获取进程的基地址

c - 使用枚举访问二维数组索引

c - 将 C MEX 文件转换为纯 C++ 时出错

c++ - 结构继承 : implicitly public or private?

c - 与结构内仅一个成员进行 union 的目的