c - C 中出现段错误

标签 c shell sorting segmentation-fault

我的程序的一小部分遇到了问题,该部分生成随机数列表,然后对它们进行 shell 排序,现在它无法完成计算,这让我认为循环尚未完成。我遇到了段错误错误,但我设法通过修复访问数组的方式的一些问题来解决这个问题。无论如何,一双新的眼睛可能对我有好处。抱歉,如果标签页已关闭。

我认为问题出在 shell_results 数组

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

int main()
{

  /*Initialize Random Array*/
  int *unsorted_list[1000000];
  int random_number;
  int i;

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

    srand ( time(NULL) );
    random_number = rand();
    unsorted_list[i] = random_number; 
  }

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

  double clock_diff;
  int j=1000000;
  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(*unsorted_list, j);
    t1= clock();

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

    /*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(*unsorted_list, j);

    /*Re-initialize a longer array*/
    //j+=1000000;       
    for(k=0; k<j; k++){

      srand ( time(NULL) );
      random_number = rand();
      unsorted_list[k] = random_number; 
    }
  }

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

最佳答案

首先,该行

int *unsorted_list[1000000];

正在使用指针

当然

int unsorted_list[1000000];

最好考虑一下何时填充

unsorted_list[i] = random_number; 

PS:只需使用srand一次。

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

相关文章:

c - 尝试使用 printfs 时神秘的 c 调试问题

bash - 如何使用docker exec命令在CLI容器中运行sh脚本?

java - 如何修复 android 中 fragment 的排序问题和数据显示?

c# - 对其中包含 NaN 的 Double 数组进行排序

bash - 可移植地过滤掉无效的 PID

c++ - 在 C++ 中使用合并排序算法合并文件

c - 在使用 C 的 Linux 中,如何将整个环境写入文件?

c - 我应该在不同的功能中还是在我现在拥有的同一个功能中执行它们?

c - 编写一个 C 程序来测量 Linux 操作系统中上下文切换所花费的时间

linux - 为什么 SunOS 说它不能执行这个 KornShell 脚本?