c - 在 C 中创建大型数组时出现段错误

标签 c arrays sorting segmentation-fault

你们在这段代码上帮了我很多。首先让我说我不太了解 C 并且正在努力做到这一点。

这是程序应该做的:

  1. 创建一个长度为 1000 万的随机数列表
  2. 使用 shell 排序函数对随机数列表进行排序(仍然无法正常工作......我认为这是我将指针传递给函数的方式)
  3. 再列出 100 万份
  4. 在记录时间的同时重复最多 1 亿次(由于某种原因,时间显示为 0.0000000)

我只是想测试这个 shell 排序程序与标准库中内置的快速排序。

我试过使用和不使用指针。注释掉的部分在完成后应该可以工作。它只会把事情搞得更糟,哈哈

请帮帮我,你们到目前为止都很棒......

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void shellSort(int *A, int n);
void checkSort(int *A, int n);

int main(){

    /*Initialize Random Array*/
    int unsorted_list[10000000];
    int *ptr = &unsorted_list[0];
    int random_number;
    int i;

    srand ( time(NULL) );
    for(i=0; i<10000000; i++){

        random_number = rand();
        unsorted_list[i] = random_number % 10000000;
    }

    //Do C Shell Sort
    double shell_results[10][2];

    double clock_diff;
    int j=10000000;
    clock_t t0, t1;
    int k;


    for(i=0;i<10;i++){



        /*Sort the list using shellSort and take the time difference*/
        t0 = clock();
        shellSort(ptr, j);
        t1= clock();

        /*Take difference in time*/
        clock_diff = (t1 - t0)/CLOCKS_PER_SEC;

        /*Add time and list length to the results array*/
        shell_results[i][0] = (double)j;
        shell_results[i][1] = clock_diff;


        /*Check to make sure the array has been sorted*/
        checkSort(ptr, j);

        /*Re-initialize a longer array*/
        //j+=1000000;
        //for(k=0; k<j; k++){
        //    random_number = rand();
        //    unsorted_list[k] = random_number % 1000000;
        //}

        printf("%d",(int)shell_results[i][0]);
        printf(" ");
        printf("%f",shell_results[i][1]);
        printf("\n");

    }





 return 0;
 }

 void shellSort(int *A, int n){



     int gap , i , j , temp;

     for (gap = n/2; gap>0; gap /=2)
         for (i=gap; i<n; i++)
             for(j = i-gap; j>=0 && A[j] > A[j+gap]; j-=gap){
                 temp = A[j];
                 A[j] = A[j + gap];
                 A[j + gap] = temp;
     }
 }



void checkSort(int *A, int n){

    int i;

    for(i=0;i<n;i++){

        if(A[i]>A[i+1]){

            printf("Error in sorting \n");
            break;
        }
    }
}

最佳答案

您可能没有 10 兆字节的堆栈空间。使该数组成为全局数组,使用 static 声明它,或使用 malloc() 动态分配它。如果您选择后者,请不要忘记 free() 它。

以后需要使用100,000,000个元素的数组时,一定要使用新的分配!

关于c - 在 C 中创建大型数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283546/

相关文章:

c - 使用 AVR 时如何查找变量的地址?

javascript - 如何在 Javascript 中使用 arry 元素作为数组名称

c++ - 为什么这个函数调用后数组发生了变化?

javascript - 如何随机化div的位置

JavaScript : Can I sort String within an array (not a normal use of sort possible)

javascript - mongoDB - 如何在多个文档中查找和排序多个字段并将它们存储在单个数组中?

c++ - fopen 和 fwrite 从多个线程到同一个文件

c - 由于某种原因分配的内存未释放 - C

c - 关于C中两种算法不同运行时间的困惑

我可以在 scanf 中使用指针来获取数组中的输入吗?