【问题标题】:Struct Segmentation fault: 11. Unable to reassign values in a struct first initialized to null结构分段错误:11. 无法重新分配结构中的值,首先初始化为 null
【发布时间】:2017-12-04 00:26:40
【问题描述】:

我对使用struct 非常陌生,所以我即将展示的一些代码可能不正确,这可能是我遇到错误的原因。我正在编写代码尝试使用struct 模拟堆栈。我目前正在尝试创建一个pushInt() 函数,该函数接受一个指向堆栈struct 和一些int 值的指针。这是puchInt() 函数的代码:

    Stack *pushInt(Stack *stack, int value)
    {
        stack->intTop = TRUE;
        stack->data.intValue = value;
        stack->next = NULL;

        return stack;
    } // end pushInt

这是我用来定义 stact struct 的代码。它是一个自引用结构,就像 like alikeList:

    struct StackNode
    {
        int intTop;

        union {
            int intValue;
            char stringValue[MAX_STRING_LENGTH];
        } data;

        struct StackNode *next; 
    };

这是我运行来测试代码功能的主要函数:

    int main()
    {
        Stack *theStack = NULL;

        //getInteger function just gets user input
        int pushValue = getInteger("value to push onto stack: ");
        theStack = pushInt(theStack, pushValue);
    }

【问题讨论】:

  • 你需要为你的节点分配内存。
  • @RetiredNinja 在我重新分配变量之前,这是否会在 pushInt() 函数中使用 malloc 来完成?

标签: c pointers struct self-reference


【解决方案1】:

theStack = pushInt(theStack, pushValue);

这里传递了 NULL 指针(用 NULL 初始化的堆栈)。所以它变成了在 pushInt 函数中取消引用 NULL 指针,从而导致 seg 错误。

你需要为变量 theStack 分配内存

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 2021-06-12
    • 2020-07-30
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多