Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 开始时的随机数组大小?_C_Arrays_Random - Fatal编程技术网

C 开始时的随机数组大小?

C 开始时的随机数组大小?,c,arrays,random,C,Arrays,Random,每次程序开始执行时,我都想创建一个随机大小的数组,但编译器总是叫我 "Error 2 error C2466: cannot allocate an array of constant size 0" 是否有任何方法可以在开始时通过SIZE=rand()%100随机选择SIZE,然后使用int-myarray[SIZE]={0}初始化数组???或者每次我都应该在开始时用一个精确的数字初始化它 int main(void) { int i; int SIZE=rand()%

每次程序开始执行时,我都想创建一个随机大小的数组,但编译器总是叫我

"Error  2   error C2466: cannot allocate an array of constant size 0"
是否有任何方法可以在开始时通过
SIZE=rand()%100
随机选择
SIZE
,然后使用
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;
    ...
}
int main(无效){
int i;
int SIZE=rand()%100;
int array2[SIZE]={0};
对于(i=0;i请注意,
rand()%100
可以并且将是0。如果您想要一个随机值1,可以使用
malloc()
calloc()
在C中执行此操作。例如

int SIZE=(rand()%100)+1; // size can be in the range [1 to 100]
int *array2 = (int*) malloc(sizeof(int)*SIZE);
但同时,数组大小只能是一个常量值

以下两个声明是有效的

int a[10];

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

int x=10;
int a[x];


最好的方法是将数组设为指针并使用:


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

您指出您使用的是Microsoft的visual studio。MS visual studio不是c99编译器(它们最多只能选择),缺少的功能之一是

使用MS VS,您能够做到的最好方法是使用以下工具动态执行此操作:

intmain(intargc,char*argv[])
{
int i;
int SIZE=rand()%100;
int*array2=malloc(SIZE*sizeof(int));//为大小int分配空间

对于(i=0;i您需要一个编译器,该编译器不会在同一时间被两次替换。VLA是在C99中添加的(但您不能像
int-array2[SIZE]={0}
)那样初始化VLA)。堆栈上变量的分配要求知道大小。使用堆(
malloc()
)如果您希望动态调整大小。我必须退出Visual Studio,那么为什么没有人使用
malloc
发布带有工作示例的答案?此解决方案的一个注意事项:此解决方案的一个注意事项:
int x=10;
int a[x];
const int y=10;
int b[y];
int SIZE=(rand()%100) + 1; //range 1 - 100
int *array2 = malloc(sizeof(int) * SIZE);
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;
}