【发布时间】:2018-07-29 03:00:21
【问题描述】:
我正在尝试在 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;
}
【问题讨论】:
-
你读过编译器警告吗?这
scanf("%d",n[i]);-->scanf("%d",&n[i]);。另外如果count大于 20 怎么办?它会导致未定义的行为。 -
什么时候是
n[-1],即i=0,j = i-1? -
给自己一个真正的 IDE,可以是 Windows 的 Visual Studio 社区,也可以是 MacOS / Linux 下免费提供的任何东西。能够在受控的调试环境中运行您的代码使得查找此类错误变得更加容易。如果您的开发环境没有停在发生崩溃的那一行,并允许您“事后”检查变量,那么是时候用更好的东西替换它了。
标签: c runtime-error insertion-sort