c - 带指针的双向链表段错误

标签 c pointers segmentation-fault

程序在推送功能中没有问题,因为我可以到达结构的成员(例如键)。如果我调用push(stack, 3),则在已经在堆上分配的newElem指针上的push函数中,键是3,但是当它被分配到堆栈时,并在push函数之外使用(在main中使用) ,它不再知道结构体成员在当前地址有什么值。所以在我看来,malloc 并没有真正起作用,并且不会将内存放在堆上,因为它无法再通过 main 函数访问?

#include <stdio.h>
#include <stdlib.h>

typedef struct list_element_t {
    int key;
    struct list_element_t* next;
    struct list_element_t* prev;

}ListElement;

ListElement* GetNewElement(int k) {
    ListElement* newElem = (ListElement*) malloc(sizeof(ListElement));
    newElem->key = k;
    newElem->next = NULL;
    newElem->prev = NULL;
    return newElem;
}

void push(ListElement* S, int k) {
    ListElement* newElem = GetNewElement(k);

    //The key is always correct here
    printf("%d\n", newElem->key);
    if(S == NULL) {
        S = newElem;
        //S is not NULL here.
        return;
    } 
    newElem->next = S;
    S->prev = newElem;
    //Put our stack in the back of the list
    S = newElem;

}

void display(ListElement* S) {
    ListElement* temp = S;
    while(temp != NULL) {
        printf("%d\n", temp->key);
        temp = temp->next;
    }
}

int main(int argc, char **argv)
{
    ListElement* stack = NULL;
    push(stack, 3);

    //stack is still NULL here????


    //Causes segmentation Fault
    printf("%d\n", stack->key);


    //Never prints anything (stack is NULL)
    display(stack);
    return 0;
}

最佳答案

push 函数中的

S 是局部变量,因此在此分配中

S = newElem;

您将newElem分配给临时对象,该对象在push结束时被销毁。如果你想修改 S 指向的内容,你应该通过指针传递它。

void push(ListElement** S, int k) {
  ListElement* newElem = GetNewElement(k);

  printf("%d\n", newElem->key);
  if(*S == NULL) {
    *S = newElem;
    return;
  } 
  newElem->next = *S;
  (*S)->prev = newElem;
  *S = newElem;
}

并在主函数中调用push函数如下

  ListElement* stack = NULL;
  push(&stack, 3);

关于c - 带指针的双向链表段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48769366/

相关文章:

c - 使用 fread 从文件中读取奇怪的文本

c++ - 通过查找位返回一个数组?

c - 将 ODBC DATE_STRUCT 转换为本地化短格式日期字符串的最佳方法

c++ - std::enable_shared_from_this<> 和多重继承

c - 使用地址运算符设置指针之间的区别

c++ - 为什么我在接受字符串输入时会出现段错误?

c++ - 按排序顺序在链表中插入多个元素时出现段错误

c - 将多维数组传递给函数并编辑值

c - C编程中的指针——坐标转换

安卓 : Catch SIGSEGV signal JNI