使用随机数创建自定义数组大小

时间:2013-10-06 20:46:44

标签: c arrays

我正在尝试编写一个返回自定义大小数组的函数,并使用随机数填充。我的整个代码是这样的:

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

int check_error(int a);
void initialize_array(int array[],int a);
void print_array(int array[],int a);
int replace(int array[],int i, int b, int c);

int main(void) 
{
    int asize, array;
    printf("Hello!\nPlease enter the size of the array:\n");
    scanf("%d", &asize);
    check_error(asize);
    while (check_error(asize)==0)
    {
            printf("Invalid input! Enter the size of the imput size again:\n");
            scanf("%d", &asize);
    }
            if (check_error(asize)==1)
    {
            initialize_array(array, asize);
    }
}

int check_error(int a)
{

    if (a> 0 &&  a <= 100)
            return 1;
    else
            return 0;
}
void initialize_array(int array[], int a)
{
    int i;
    srand(time(NULL));
    for(i=0; i < a; i++)
    {
            array[i]=rand()%10;
    }
}

具体而言,我需要帮助initialize_array按预期工作。

1 个答案:

答案 0 :(得分:2)

在您的代码中,删除以前的数组定义,然后执行以下操作:

if (check_error(asize)==1) {
        int array[asize];
        initialize_array(array, asize);
        // other stuff here
}

请注意,数组仅在if(check_error)语句的{}之间有效。

相关问题