2013-03-07 20 views
1

你们已经帮助了我很多这个代码。让我先说我不太熟悉C,并努力做到这一点。在C中创建大型数组时出现了分段错误

这档节目应该做的:

1)创建长度为10万元 2)的随机数的列表排序使用shell排序功能(仍然不工作正确的随机数列表...我认为它如何,我传递函数指针) 3)做一个列表1百万更长

4)重复了高达1亿,同时记录时间(时间显示为0.0000000出于某种原因)

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

我试过有和没有指针...当它的done..It只是弄乱的东西更多的笑

请帮我,你们一直这么伟大到目前为止注释掉部分应该工作...

#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; 
     } 
    } 


} 

回答

2

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

后来,当您需要使用100,000,000元素数组时,请确保使用它的新分配!

+0

我应该从大小100,000,000的数组开始?或继续做新的? – 2013-03-07 23:11:15

+0

你当然可以那样做,是的。 – 2013-03-07 23:16:13

0

那么你没有办法在堆栈上有足够的可用空间。使用malloc()从堆中分配它。请记住随后释放()。