I'm trying to make a variable sized array in c.
The array keeps on coming back as having a value of -1.
What I want to do is to make an array of size size
and then incrementally add values to it. What am I doing wrong?
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;
}
What you need is a dynamic array. One that you can allocate an initial size, then use realloc
to increase the size of it by some factor when appropriate.
I.e.,
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. */
Use this function to grow it:
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. */
}
}
You should probably allocate (and subsequently free) the array dynamically, like so:
int *ar = malloc(sizeof(int) * size);
for (int b = 0; b < size; b++)
{
...
}
// do something with ar
free(ar);
if you make size a const int that should work. Also, if your array is inside a function and size is an argument of said function, that should work too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With