-1

每次程序首先执行时,我都想创建一个随机大小的数组,但编译器对我大喊大叫

"Error  2   error C2466: cannot allocate an array of constant size 0"

有什么方法可以让我在开始时随机选择SIZEbySIZE = rand() % 100然后用int myarray[SIZE]={0}??? 还是我应该每次都在开始时用一个确切的数字初始化它?

int main(void) {
    int i;
    int SIZE=rand()%100;
    int array2[SIZE]={0};

    for(i=0;i<SIZE;i++)     //fill the array with random numbers
        array2[i]=rand()%100;
    ...
}
4

4 回答 4

2

您表示您正在使用 Microsoft 的 Visual Studio。MS Visual Studio不是c99 编译器(他们充其量只是挑选),缺少的功能之一是VLAs

你可以用 MS VS 做的最好的事情是动态地使用malloc()

int main(int argc, char *argv[])
{
    int i;
    int SIZE=rand()%100;
    int *array2=malloc(SIZE * sizeof(int));  // allocate space for SIZE ints

    for(i=0;i<SIZE;i++)     //fill the array with random numbers
        array2[i]=rand()%100;
    free(array2);   // free that memory when you're done.
    return 0;
}

如果要切换编译器,还有其他选择。

于 2013-05-02T18:10:21.690 回答
1

请注意,rand()%100可以和将是 0。如果你想要一个随机值 1 <= n <= 100 那么你需要使用(rand()%100)+1

于 2013-05-02T18:02:45.047 回答
1

您可以在 C 中使用malloc()calloc()来执行此操作。例如,

int SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
int *array2 = (int*) malloc(sizeof(int)*SIZE);

但同时,数组大小只能是一个常数值。

以下两个声明是有效的。

int a[10];

#define MAX 10
int b[MAX];

但是如果您尝试使用以下方法进行声明,则会出现错误。

int x=10;
int a[x];

const int y=10;
int b[y];
于 2013-05-02T18:05:48.757 回答
1

最好的方法是使您的数组成为指针并使用malloc

int SIZE=(rand()%100) + 1; //range 1 - 100
int *array2 = malloc(sizeof(int) * SIZE);

之后,您可以array2像使用数组一样使用。

于 2013-05-02T18:09:03.000 回答