c - 如何避免插入排序中的 SIGSEGV 错误
问题描述
我正在尝试在 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 错误?好吧,它是good old Segmentation fault
error 的别称,基本上就是你在访问无效内存(即不允许访问的内存)时遇到的错误。
tl;博士:更改
scanf("%d",n[i]);
为scanf("%d",&n[i]);
。您正在尝试使用 读取初始值scanf("%d",n[i]);
,这会引发分段错误错误,因为scanf
需要将读取的值放入其中的地址,但您真正要做的是传递 的值,n[i]
就好像它是一个地址一样(它不是,因为,由于您尚未为其设置任何值,因此它几乎只是内存垃圾)。更多关于这里。tl;博士:更改
int n[20];
为int n[count]
。您的数组声明int n[20];
将最多存储 20 个整数,如果有人想插入 21 个或更多值会怎样?您的程序保留了一定的堆栈(内存)空间,如果您超过该空间,那么您将偶然发现另一个程序的空间,并且警察(内核)会逮捕您(分段错误)。提示:尝试插入 21 和 100 值,看看会发生什么。tl;博士:更改
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 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
调试。
推荐阅读
- r - 在进行跨类别聚合时,R data.table 快速追加列总数的方法?
- c++ - 枚举作为模板参数
- sql - 在 SQL 中将 45615564.5441 之类的数字转换为 45,615,564
- android - Android应用内计费:如果应用内购买由主设备帐户控制,那么如何防止通过帐户
- r - 在 dockerization 期间安装了错误的 R 版本
- architecture - 如何仅在事件驱动架构中接收到两个或多个事件后才触发动作?
- c# - 如何确定客户端是否可以使用 IdentityServer4 调用 api 端点
- javascript - 如何在本地主机上开发时使 Progressive Web App 的启动画面图标可用
- algorithm - 查找关节点组
- date - #docusignAPI 获取数据发送时间