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

标签 c arrays sorting

我正在编写代码来对 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/

相关文章:

Javascript - 比较两个数组。如果两者都找到对象,则更改它

javascript - 在 POST 正文中发送一个数组

python - 保持可变元素的排序列表是最新的

c - 赋值运算符的重新定义

C 文件中的字符数

c - 小端结果

java - 尝试对 .txt 文件中的 double 进行排序时遇到问题

arrays - 如何对日期数组使用排序函数?

c - 了解 SLIST -queue.h

c++ - 是否可以确定(在运行时)功能是否已实现?