gpt4 book ai didi

c - 排序程序 C 中的段错误

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

我正在编写代码来对 int 的 txt 文件进行排序,然后在用户要求某个索引处的数字时显示它们,但每次运行我的代码时都会出现段错误。我该怎么做才能解决这个问题?

void insert_sorted(long *sorted, int count, long value)
{
int i = 0;

sorted[1024] = value;
if (count == 0) return;
for (i = count; i >= 0; i--) {
if (value < sorted[i - 1])
sorted[i] = sorted[i - 1];
else break;
}
sorted[i] = value;
}
int main(int argc, char *argv[])
{
FILE *infile = NULL;
int count = 0;
long sorted[1024];
long value;
int i = 0;
if (argc < 2) {
fprintf(stderr, "Usage : %s <file_name>/n", argv[0]);
return 1;
}
infile = fopen(argv[1], "r");
if (NULL == infile) {
perror("fopen");
return -1;
}
/* while file not ends */
while (!feof(infile)) {
fscanf(infile, "%ld\n", &value); /* fetch value */
insert_sorted(sorted, count, value); /* sort */
++count; /* increase number of sorted values */
}
/* display values */
printf("Enter Index : ");
int index;
scanf("%d", &index);
if (index == -1)
fclose(infile);
printf("%d ", sorted[index]);

/* cleanup */
if (infile) {
fclose(infile);
infile = NULL;
}
return 0;
}

最佳答案

sorted[1024]中的操作=value;会使你的程序崩溃。排序后的数组大小只有1024,所以最大索引为1023。

解决这个问题的一种方法是在 main() 函数中将 sorted 的大小更改为 1025。

for 循环中的另一个操作可能会使程序崩溃:当 i =0 时,访问已排序的 [i - 1] 将捕获异常。

关于c - 排序程序 C 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52229535/

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