c - 段错误回路 C99

标签 c arrays loops segmentation-fault quicksort

此代码是一个更大程序的一部分。代码中有一个 main 函数,它运行良好,如果它困惑,请原谅。在第二个 while 循环中的函数 Quick_mode_time 中,我遇到了一个段错误,我不明白我是如何弄乱数组导致这个的。如果有人能指出我正确的方向,我会很高兴!

#include <stdio.h>
#include <time.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>

#define timing_start() start = clock();
#define timing_end(f) msec = (double)(clock()-start) * 1000000.0 /CLOCKS_PER_SEC; \
    printf("Calling "#f " takes %10.2f microseconds!\n", msec);

void Quick_mode_time()
{
    srand(time(NULL));
    int end=500,final=5000;
    int a[end],beginning=0;
    double t1,t2,t_tot;
    printf("***************COMPARISON***************\n");

    printf("                quicksort       bubblesort      (in microseconds)\n");
    while(end!=final){

        while(beginning<end)
        {
            a[beginning]=rand()%end;  // <--- This causes a segmentation fault
            beginning++;
        }
        printf("N=%d",end);

        t1=clock();
        quicksort_time(a,0,end);

        t2=clock();
        t_tot= (double)(t2-t1)*1000/CLOCKS_PER_SEC;
        printf("\t%7.3f\t", t_tot);
        end+=500;
    }
}

void quicksort_time(int x[],int first,int last){
    int pivot,j,temp,i;
    // The Quick Sorting algorithim is below!
    if(first<last){
        pivot=first;
        i=first;
        j=last;

        while(i<j){
            while(x[i]<=x[pivot]&&i<last)
                i++;
            while(x[j]>x[pivot])
                j--;
            if(i<j){
                temp=x[i];
                x[i]=x[j];
                x[j]=temp;
            }
        }

        temp=x[pivot];
        x[pivot]=x[j];
        x[j]=temp;
        quicksort_time(x,first,j-1);
        quicksort_time(x,j+1,last);
    }
}

最佳答案

这一行:

int a[end]

创建一个包含 500 个整数的数组(end 在前面的行中设置为 500)

这一行

a[beginning]=rand()%(end+1-end)+end;

写入 a[beginning] 只要 beginning 小于 500 就可以。

这似乎是由上面的这一行检查的:

while(beginning<end)

但稍后在您的代码中,您有:

end+=500;

突然间,end 可以 > 500,这意味着 beginning 可以 > 500。这意味着你写在你的数组边界之外。

一个解决方法是更改​​您的声明,使 a 足够大:

int a[final]

关于c - 段错误回路 C99,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040048/

相关文章:

java - 调整数组大小: How much should it be done?

java - 如何读取数组中的字符输入?

javascript数组取消移位一些元素

使用 while 循环的 Java 菜单循环

c - 交换字符串按值而不是引用传递?

C程序返回数组

c - 在 Microsoft Windows 平台上进行调试

c - 使用 realloc 释放 2d 字符数组

javascript - 尝试使用数组和循环重写 JS 测验——正确答案在哪里?

ruby - 如何使用字符串数组循环遍历字符串以查找匹配项?