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

dub*_*eat 10 c arrays

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

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

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

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;
}
Run Code Online (Sandbox Code Playgroud)

jer*_*jer 9

你需要的是一个动态数组.您可以分配初始大小,然后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. */
Run Code Online (Sandbox Code Playgroud)

使用此功能来增长它:

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. */
    }
}
Run Code Online (Sandbox Code Playgroud)