为什么大的可变长度数组具有固定值-1,即使在C中赋值?

我正在尝试在c中创建一个可变大小的数组。

数组继续返回,其值为-1。

我想要做的是创建一个大小的数组,然后逐步添加值。 我究竟做错了什么?

 int size = 4546548; UInt32 ar[size]; //soundStructArray[audioFile].audioData = (UInt32 *)malloc(sizeof(UInt32) * totalFramesInFile); //ar=(UInt32 *)malloc(sizeof(UInt32) * totalFramesInFile); for (int b = 0; b < size; b++) { UInt32 l = soundStructArray[audioFile].audioDataLeft[b]; UInt32 r = soundStructArray[audioFile].audioDataRight[b]; UInt32 t = l+r; ar[b] = t; } 

你需要的是一个动态数组。 您可以分配初始大小,然后使用realloc在适当的时候通过某种因素增加它的大小。

也就是说,

 UInt32* ar = malloc(sizeof(*ar) * totalFramesInFile); /* Do your stuff here that uses it. Be sure to check if you have enough space to add to ar and if not, call grow_ar_to() defined below. */ 

使用此function来增长它:

 UInt32* grow_ar_to(UInt32* ar, size_t new_bytes) { UInt32* tmp = realloc(ar, new_bytes); if(tmp != NULL) { ar = tmp; return ar; } else { /* Do something with the error. */ } } 

您应该动态分配(并随后释放)数组,如下所示:

 int *ar = malloc(sizeof(int) * size); for (int b = 0; b < size; b++) { ... } // do something with ar free(ar); 

如果你使size成为一个应该工作的const int。 此外,如果您的数组在函数内部并且size是所述函数的参数,那么它也应该起作用。

C在定义数组大小时不允许使用变量,你需要做的是使用malloc ,这应该给你一个想法:

 UInt32* ar; ar = (UInt32*) malloc(size * sizeof(UInt32)); 

不要忘记随后将其释放