gpt4 book ai didi

c - C中数组排序算法中的段错误

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

我是编程初学者,正在学习 K.N.King 的“C 编程:一种现代方法”。现在我正在尝试进行第 9 章的编程项目 1,但我一直遇到段错误,我不确定代码有什么问题。感谢任何更正!

这些是说明:

编写一个程序,要求用户输入一系列整数(它存储在一个数组中),然后通过调用函数 selection_sort 对这些整数进行排序。当给定一个包含 n 个元素的数组时,selection_sort 必须执行以下操作:
1.搜索数组找到最大的元素,然后将其移动到数组的最后一个位置。
2.递归调用自身对数组的前n-1个元素进行排序。

这是我的代码:

#include <stdio.h>

void selection_sort(int n, int a[n]);

int main(void)
{
int n;

printf("Number of integers to sort: ");
scanf("%d", &n);

int a[n];

printf("Enter the integers: ");
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}

selection_sort(n, a);

printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d", a[i]);

return 0;
}

void selection_sort(int n, int a[n])
{
int swap, max = a[n - 1];

for (int i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
swap = a[n - 1];
a[n - 1] = max;
a[i] = swap;
}
}
if (n > 1)
selection_sort(n - 1, a);
}

编辑:将 while (n > 1) 更改为 if (n > 1),现在它可以完美运行。但为什么它不能与 while 一起使用?

最佳答案

您需要一个不调用 selection_sort 的条件。现在,您的 selection_sort 总是 调用 selection_sort,这会导致无限循环。

并且,由于您在每一步都递减 n,因此在某一时刻它变为负数,并且您开始访问 a[-1],这是错误的。

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

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