我正在尝试在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
错误的另一个名称,它基本上是访问无效内存(即不允许访问的内存(时出现的错误。
-
tl;dr:将
scanf("%d",n[i]);
更改为scanf("%d",&n[i]);
。您正试图用scanf("%d",n[i]);
读取初始值,这会引发分段错误,因为scanf
期望地址将读取的值放入其中,但您真正要做的是传递n[i]
的值,就好像它是一个地址一样(事实并非如此,因为您还没有为它设置任何值,所以它几乎只是内存垃圾(。点击此处了解更多信息。 -
tl;dr:将
int n[20];
更改为int n[count]
。您的数组声明int n[20];
最多将存储20个整数,如果有人想要插入21个或更多的值,会发生什么?你的程序保留了一定的堆栈(内存(空间,如果你超过了这个空间,那么你会偶然发现另一个程序的空间,警察(内核(会逮捕你(分段错误(提示:尝试插入21个值,然后插入100个值,看看会发生什么。 -
tl;dr:将
for(i = 0; i < count; i++) {
更改为for(i = 1; i <= count; i++) {
。这是索引的逻辑问题,从i = 0
开始一直到i = count - 1
,这在大多数数组迭代情况下都是正确的,但由于j
假设i
之前的索引值,因此需要i
从1
开始(因此j
是0
,否则第一次迭代中的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 elementsn",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 elementsn");
for(i = 0; i < count; i++) {
printf("%dn",n[i]);
}
return 0;
}
编辑:如果你在使用在线IDE时遇到问题,可以考虑在本地运行你的程序,这会节省很多时间,而且:你永远不知道在线IDE使用什么内核版本或魔法来运行你的代码(相信我,当你用C——相当低级别的语言编码时,这些东西有时会有所不同(。我喜欢使用Vim
作为文本编辑器,gcc
用于编译,gdb
用于调试。