c - 我程序中的段错误

标签 c segmentation-fault

我的排序程序导致“段错误 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 之后的索引,例如,如果 i012

关于c - 我程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809866/

相关文章:

java - 有限状态机程序

c - 为什么这个指针出现段错误 C?

mysql - DBI 和 MySQL 的奇怪的 ruby​​ 段错误

c - 程序运行并显示输出后段错误核心转储

c - 使用 out params 查找 float 组中的最小和最大元素

c - 如何比较无符号和有符号长变量?

c - C中双斜杠后的分号

c - C语言中通过整数转换进行 float 比较

linux - x86 内存访问段错误

c - 段错误检查月份