gpt4 book ai didi

c - 数组声明导致 while 循环出现奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:48 25 4
gpt4 key购买 nike

我最近在我的 c 程序中遇到了非常奇怪的行为。我删除了大部分代码只是为了找出问题发生在你们身上的地方。

程序在当前状态下的目的是从 txt 文件中读取作业并将内容打印到屏幕上。在这里:

#include <stdio.h>

int main(){
char* user;
char process;
int arrival;
int duration;

scanf("%*[^\n]"); //skipping header in the file.

while(!feof(stdin))
{
scanf("%s\t%c\t%d\t%d\n", user, &process, &arrival, &duration);
printf("%s\t%c\t%d\t%d\n", user, process, arrival, duration);
}

int x[5]; //<----- Causing the weird behaviour
}

我输入的文件是:

User    Process Arrival Duration
Jim A 2 5
Mary B 2 3
Sue D 5 5
Mary C 6 2

我遇到的问题是每当我声明 int x 数组时,无论它是在我的代码的底部还是顶部,while 循环进入无限循环或程序段错误。

根据我声明数组的大小,它会进入无限循环或段错误。例如,如果我声明数组的大小为 5,它就会进入无限循环。但是,如果我将数组的大小声明为 2,它将出现段错误。

我正在通过运行来编译我的程序:

gcc -o myprog myprog.c

我通过运行管道文件:

cat jobs.txt | ./myprog

还值得注意的是,程序在没有 int x 数组声明的情况下运行良好。

我完全不知道可能是什么问题,有什么想法吗?

最佳答案

由于未初始化的指针 user,您有未定义的行为。 user 必须指向能够存储您想要的内容的内存区域(例如,参见 malloc())。

关于c - 数组声明导致 while 循环出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507042/

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