c - 具有许多数字的随机数组出现错误

标签 c random header

我有一个作业要做:我需要测量一个包含 100000 个数字的随机数组中的冒泡排序的时间。当我尝试随机生成数字时出现错误。此外,如果我不随机生成数字,我每次都会得到 0。 到目前为止我已经做到了:

main.c 

int main()
{
    int *a,n = 0;
    srand(time(0));
    beolvas(&a,&n,"be.txt");
    clock_t start,stop;
    start = clock();
    bubblesort(a,n);
    stop = clock();
    float timespent = (stop - start)/CLOCKS_PER_SEC;
    printf("%f\n",timespent);

    kiir(a,n);
    free(a);
    return 0;
}

kibe.c(sorry I write it bad)

void beolvas(int **a,int *n,const char * file)
{
    int i;
    FILE * fin;
    fin = fopen("be.txt", "rt");
    *a = (int*)malloc(*n*sizeof(int));
    if(a == 0){printf("Error");return 0;}
    for(i = 0; i < 100000; ++i){
        *a = rand() % 100;
    }
    fclose(fin);
}
void bubblesort(int *a, int n)
{
    int i,j,csere;

    for(i = 0; i < n-1; ++i){
        for(j = 0; j < n - i -1; ++j){
            if (a[j] > a[j + 1]){
                csere = a[j];
                a[j] = a[j + 1];
                a[j + 1] = csere;
            }
        }
    }
}

void kiir(int *a,int n)
{
    int i;
    for(i = 0; i < n; ++i){
        printf("%i ",a[i]);
    }
}

正如你所见,我需要使用标题...这真的很无聊...

编辑

现在我完全重写了所有程序,没有错误,没有警告,但它没有打印出数组,排序时间仍然是0。我忘了做什么?为什么我的 write 函数什么也不做?

sema.c

void read(int *a,int n)
{
    int i;
    scanf("%d",&n);
    a = (int*)malloc(n*sizeof(int));
    if(a == 0){printf("Error");return 0;}
    for(i = 0; i < n; ++i){
        a[i] = rand() % 100;
    }
}

void bubblesort(int *a,int n)
{
    int i,j,csere;

    for(i = 0; i < n-1; ++i){
        for(j = 0; j < n - i -1; ++j){
            if (a[j] > a[j + 1]){
                csere = a[j];
                a[j] = a[j + 1];
                a[j + 1] = csere;
            }
        }
    }
}
void write(int *a,int n)
{
    int i;
    for(i = 0; i < n; ++i){
        printf("%i ",a[i]);
    }
}

sema.h

void read(int*,int*);
void write(int*,int);
void bubblesort(int*,int);

main.c

int main()
{
    double *a = NULL ,n = 0;
    read(&a,&n);
    clock_t start,stop;
    start = clock();
    bubblesort(a,n);
    stop = clock();
    float elapsedTime = (stop - start)/CLOCKS_PER_SEC;
    printf("%f",elapsedTime);
    write(a,n);

    free(a);
    return 0;
}

最佳答案

void beolvas(int **a,int *n,const char * file);a 声明为指向指针的指针。

但是这一行:

*a = rand() % 100;

仅取消引用它一次并将值分配给指针(实际上导致内存泄漏,因为它之前被malloc编辑)

所以你会得到各种未定义的行为。

关于c - 具有许多数字的随机数组出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35512727/

相关文章:

不带参数和括号的调用函数

c - 循环递增并保持状态

angular - 如果没有用户以 angular 4 登录,标题应该隐藏

c++ - 在 C++ 中包含头文件时的循环类依赖

c++ - 通过 objdump 链接没有头文件的 so 库

c - 在 xv6 中实现 lseek

c++ - 无法在 Visual C++ 2010 中使用 default_random_engine 字段创建类

java - 大气噪声和生成随机数java

ruby - 以随机顺序将数组拆分为多个数组 - Ruby

c - 用 Void 函数填充结构数组