简体   繁体   English

异常段错误:无法在全局之外声明变量?

[英]Unusual Seg Fault: Cannot declare variables outside global?

I've been stuck for a few hours working on ac program that will loop 5 times while the user inputs 5 integers for a linked list. 我在交流程序上工作了数小时,该程序将循环5次,而用户为链接列表输入5个整数。 Somehow I cannot declare variables in my main without getting a segmentation fault in the print function. 不知何故,我无法在main中声明变量,而不会在print函数中遇到分段错误。

My typedef: 我的typedef:

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

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

My main 我的主要

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

My insert function 我的插入功能

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

My print function 我的打印功能

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");
    }
}

For some reason, if I set the program to loop until the user inputs a number, say, -1, the program is fine and no problem. 出于某种原因,如果我将程序设置为循环播放,直到用户输入一个数字(例如-1),那么程序就可以了,并且没有问题。 But I cannot declare any other integers (even if they have no use) without getting a seg fault. 但是我不能在没有seg错误的情况下声明任何其他整数(即使它们没有用)。 Can anyone help me figure out why this is happening and what I can do to fix it? 谁能帮助我弄清楚为什么会这样,以及我可以采取什么措施来解决? I would like to be led down the path, but not necessarily told the answer. 我想被带走,但不一定告诉答案。

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

Please make above change in main and remove global declaration of y . 请对main进行上述更改,并删除y全局声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM