c - 异常段错误: Cannot declare variables outside global?

标签 c linked-list segmentation-fault global-variables

我已经在一个 C 程序上工作了几个小时,当用户为链接列表输入 5 个整数时,该程序将循环 5 次。不知何故,我无法在主函数中声明变量而不在打印函数中出现段错误。

我的类型定义:

typedef struct node_{
    int value;
    struct node_* next;
}node;

int y = 0; //If this is made local in main, seg fault

我的主要内容

int main(void)
{
    node *head;
    int x;
    //int y; /*Does not work here*/
    while(y < 5)
    {
        printf("Insert: ");
        scanf("%d", &x);

        head = insert_top(head, x);
        print(head);
        y ++;
    }
    free(head);
    return 0;
}

我的插入功能

node* insert_top(node* head, int value)
{
    node *newHead;
    newHead = malloc(sizeof(node));

    newHead->value = value;

    if(head == NULL)
    {
        head = newHead;
        head->next = NULL;
        return head;
    }
    else
    {
        newHead->next = head;
        head = newHead;
        return head;
    }
}   

我的打印功能

void print(node* head)
{
    if(head == NULL)
    {
        printf("List is empty\n");
        return;
    }
    else
    {
        while(head != NULL)
        {
            printf("%d->", head->value);
            head = head->next;
        }
        printf("NULL\n");
    }
}

由于某种原因,如果我将程序设置为循环,直到用户输入一个数字,例如-1,则程序很好,没有问题。但我无法在不出现段错误的情况下声明任何其他整数(即使它们没有用)。谁能帮我弄清楚为什么会发生这种情况以及我可以采取什么措施来解决它?我希望有人引导我走上这条路,但不一定告诉我答案。

最佳答案

node *head = NULL;
int y = 0; /*Does not work here*/

请在main中进行上述更改并删除y的全局声明。

关于c - 异常段错误: Cannot declare variables outside global?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21717427/

相关文章:

c++ - float : Disable specific exception

c - 为什么 `int *p = (char *) &num' 会导致警告?

c++ - 与枚举时出现段错误

c - 在 C 解决方案段错误中反转字符串

C++ 二进制文件添加记录、搜索和替换

c - 汉明重量(数字中1的个数)混合C与组件

java - Java 的 LinkedList 是否优化为在必要时反向执行 get(index)?

c - 追踪段错误 11

c - 从具有特定值的链表中删除节点

python - 在 python 中使用链表实现堆栈。 pop 方法的问题和有关可变性的问题