C 如何避免插入排序中的SIGSEGV错误
我正在尝试用C语言实现插入排序算法。 但我得到的只是在线IDE中的SIGSEGV错误,并且输出不会显示在Code::Blocks中。如何避免此类错误C 如何避免插入排序中的SIGSEGV错误,c,runtime-error,insertion-sort,C,Runtime Error,Insertion Sort,我正在尝试用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
#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;
}
#包括
#包括
int main()
{
/*这里i和j表示循环计数器,temp表示交换
元素总数计数,元素数组*/
整数i,j,温度,计数;
printf(“您要输入多少个数字”);
scanf(“%d”、&count);
int n[20];
printf(“输入%d个元素”,计数);
//在数组中存储元素
对于(i=0;i
您的代码有几个问题。首先,什么是SIGSEGV错误?好吧,这是旧错误的另一个名称,基本上是访问无效内存(即不允许访问的内存)时出现的错误
scanf(“%d”,n[i])代码>到scanf(“%d”、&n[i])代码>。您正在尝试使用scanf(“%d”,n[i])读取初始值
,这会引发分段错误,因为scanf
需要地址,将读取的值放在该地址中,但您真正做的是传递n[i]
的值(事实并非如此,因为您还没有为它设置任何值,它几乎只是内存垃圾)
int n[20];
更改为int n[count]
。您的数组声明int n[20];
最多将存储20个整数,如果有人想插入21个或更多值,会发生什么情况?您的程序保留了某个堆栈(内存)空间,如果您超出了该空间,那么您将偶然发现另一个程序的空间,警察(内核)将逮捕您(分段错误)。提示:尝试插入21个值,然后插入100个值,看看会发生什么for(i=0;i
更改为for(i=1;我已阅读了编译器警告?此scanf(“%d”,n[i]);
-->scanf(“%d”,“n[i]);
如果count大于20会导致未定义的行为。那么n[-1]将是什么
即当i=0
,j=i-1
时,为自己准备一个真正的IDE,可以是Visual Studio community for Windows,也可以是MacOS/Linux下免费提供的任何东西。能够在受控调试环境中运行代码可以让查找此类错误变得非常容易。如果您的开发环境没有停止运行在崩溃发生的地方,并允许您“事后”检查变量,是时候用更好的方法替换它了。谢谢,我忘了添加“&”在scanf中,为什么我不会因为这个错误得到一个错误?如果您使用的是在线IDE,那么编译器的选项可能对您不可用。但是您可以选择并指定选项-Wall
(全部警告),您应该会看到一条警告对此表示不满。警告:格式“%d”要求参数的类型为“int*”,但参数2的类型为“int”[-Wformat=]
此外,请确保在答案上标记一个复选框,如果它对您有帮助:)
#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;
}