gpt4 book ai didi

c - 如何避免插入排序中的 SIGSEGV 错误

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

我正在尝试用 C 实现插入排序算法。但我得到的只是在线 IDE 中的 SIGSEGV 错误,并且输出没有显示在 Code::Blocks 中。如何避免此类错误。

#include <stdio.h>
#include <stdlib.h>

int main()
{
/* Here i and j are for loop counters, temp for swapping
count for total number of elements,array for elements*/

int i, j, temp, count;
printf("How many numbers are you going to enter");
scanf("%d", &count);
int n[20];
printf("Enter %d elements", count);

// storing elements in the array
for(i = 0; i < count; i++) {
scanf("%d", n[i]);
}

// Implementation of insertion sort algorithm
for(i = 0; i < count; i++) {
temp = n[i];
j = i - 1;

while(temp < n[j]) {
n[j+1] = n[j];
j = j - 1;
}
n[j+1] = temp;
}

printf("Order of sorted elements");
for(i = 0; i < count; i++) {
printf("%d", n[i]);
}

return 0;
}

最佳答案

您的代码存在一些问题。首先,什么是 SIGSEGV 错误?好吧,这是好旧的另一个名字 Segmentation fault 错误,这基本上是您在访问无效内存(即不允许访问的内存)时遇到的错误。

  1. tl;dr: 更改 scanf("%d",n[i]);scanf("%d",&n[i]); .您正在尝试使用 scanf("%d",n[i]); 读取初始值,这会引发段错误,因为 scanf期望在其中放置读取值的地址,但您真正做的是传递 n[i]就好像它是一个地址(它不是,因为你还没有为它设置任何值,它几乎只是内存垃圾)。更多关于 here .

  2. tl;dr: 更改 int n[20];int n[count] .你的数组声明 int n[20];将最多存储 20 个整数,如果有人想插入 21 个或更多值会怎样?您的程序保留了一定的堆栈(内存)空间,如果您超过该空间,那么您将偶然发现另一个程序的空间,警察(内核)将逮捕您(段错误)。 提示:尝试插入 21,然后插入 100 个值,看看会发生什么。

  3. tl;dr: 更改 for(i = 0; i < count; i++) {for(i = 1; i <= count; i++) { .这是您索引的逻辑问题,您从 i = 0 开始一直到i = count - 1这在大多数数组迭代情况下都是正确的,但作为 j假定索引值在 i 之前, 你需要 i1 开始(所以 j0 ,否则在第一次迭代中是 j = -1 (不是有效索引))。

我的最终代码如下。希望对您有所帮助,编码愉快!

#include <stdio.h>
#include <stdlib.h>

int main() {
/*Here i and j are for loop counters,temp for swapping
count for total number of elements,array for elements*/
int i, j, temp, count;
printf("How many numbers are you going to enter?\n");
scanf("%d",&count);
int n[count];
printf("Enter %d elements\n",count);
//storing elements in the array
for(i = 0; i < count; i++) {
scanf("%d", &n[i]);
}
//Implementation of insertion sort algorithm
for(i = 1; i <= count; i++) {
temp = n[i];
j = i-1;
while(temp < n[j]) {
n[j+1] = n[j];
j--;
}
n[j+1] = temp;
}
printf("Order of sorted elements\n");
for(i = 0; i < count; i++) {
printf("%d\n",n[i]);
}
return 0;
}

编辑:如果您在使用在线 IDE 时遇到问题,请考虑在本地运行您的程序,这样可以节省大量时间,此外:您永远不知道在线 IDE 使用的内核版本或魔法运行你的代码(相信我,当你用 C 编写代码时——相当低级的语言,这些东西有时会有所不同)。我喜欢使用 Vim 的所有根样式作为文本编辑器和 gcc 用于编译以及 gdb 用于调试。

关于c - 如何避免插入排序中的 SIGSEGV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51576860/

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