我的排序程序导致“段错误 11”:
#include <stdio.h>
int main()
{
// Asking user for number of inputs in an array
int n;
do {
printf ("enter the number of intigers you want to sort\n");
scanf("%d",&n);
}while (n<=1);
int sort [n];
printf ("please enter %d numbers\n",n);
for (int i=0; i<n; i++) {
scanf("%d",&sort[i]);
}
printf("you entered\n ");
for (int i=0; i<n; i++) {
printf(" %d ",sort[i]);
}
printf("\n");
int k,c,i,x;
for (i=0;i<n;i++) {
if (sort[i]<sort[i-1]){
k=i-2;
while (sort[k]>sort[i]){
k--;
}
k++;
x =sort[i];
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
}
}
printf ("Sorted numbers :-\n");
for (int i=0; i<n; i++) {
printf ("%d ",sort[i]);
}
printf ("\n");
return 0;
}
现在上网查了一下,是因为某个变量的值超过了系统内存限制造成的。但是无法理解那个概念。
最佳答案
for (i=0;i<n;i++)
{
if (sort[i]<sort[i-1])
您正在越界访问数组。也许您想从 1
开始循环。另外
k=i-2;
while (sort[k]>sort[i])
将访问 0
之后的索引,例如,如果 i
是 0
或 1
或 2
关于c - 我程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809866/