Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a large variable length array has a fixed value -1 even if assigned to in C?

Tags:

arrays

c

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;
}
like image 574
dubbeat Avatar asked Nov 24 '10 17:11

dubbeat


3 Answers

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. */
    }
}
like image 51
jer Avatar answered Nov 15 '22 18:11

jer


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);
like image 38
Wyatt Anderson Avatar answered Nov 15 '22 18:11

Wyatt Anderson


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.

like image 45
Hervé Avatar answered Nov 15 '22 19:11

Hervé