【发布时间】:2021-01-02 17:41:44
【问题描述】:
我的目标是整理出一个名为“3_1.txt”的 txt 文件中的数字数组。我已经在 C 语言中实现了代码来对称为“sort.c”的数字进行排序。这是我一直在做的学校作业,但似乎看不出我哪里出错了。我认为某些事情不正确的唯一原因是因为在 GitHub 教室 feedback / debug 上说以下内容 --> 错误 ❌ sort.c:运行动态测试 ::error::Error: Exit with code: 1 and signal: null
我有什么遗漏吗?
sort.c 在 C 语言中:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* The following code is supposed to sort the .txt file
when ran through the terminal. */
int main(int argc, char*argv[]){
int numbers[22];
int i;
int n = sizeof(numbers)/sizeof(numbers[0]);
FILE *myFile;
myFile = fopen(argv[1], "r");
if(myFile == NULL){
printf("Error reading file\n");
exit (0);
}
for(i = 0; i < 22; i++){
fscanf(myFile, "%d", &numbers[i]);
}
selectionSort(numbers, n);
printArray(numbers, n);
fclose(myFile);
return 0;
}
void swap(int *xs, int *ys){
int temp = *xs;
*xs = *ys;
*ys = temp;
}
void selectionSort(int arr[], int n){
int i, j, min_idx;
for (i = 0; i < n-1; i++){
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size){
int i;
for (i = 0; i < size; i++){
printf("%d ", arr[i]);
}
}
// EOF
3_1.txt
14 15 6
23 20
5 10
67 80
1 5 7 3 4
54 55
96
8
12
37 25 37
【问题讨论】:
-
你在运行程序时指定了文件名吗?
-
直接运行代码实际结果如何?
-
另外,您确定测试输入始终是
22数字吗?像代码中这样的幻数通常不是好的做法,在这种情况下,如果输入包含多于或少于 22 个数字,则会导致问题。 -
@VladfromMoscow 是的,我有。如果我错了,请告诉我...我使用了 ./sort.out 3_1.txt。
-
@kaylum 魔数 22 的问题是提供的测试文件 3_1.txt 正好是 22 个整数。目前,该程序专门针对该确切数量的整数工作。有没有办法用 malloc() 的动态数组或可变长度数组重构这段代码?
标签: c debugging malloc github-classroom