gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:38:31 24 4
gpt4 key购买 nike

我已经在一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com