views:

108

answers:

2

I have a C array in Objective C defined as follows:

id keysArray;

Then in an if block, i would like to redefine the array based on a condition:

if (somethingIsTrue){
    id keysArray[4][3];
}
else {
    id keysArray[6][1];
}

Then outside of the if block, when i access the array, i get errors saying the keysArray does not exist.

Thanks.

+2  A: 

That's because when you leave the scope of the if, all local variables defined within that scope are destroyed. If you want to do this, you will have to use dynamic allocation. I don't know the Objective C way of doing things, but in regular C you shall use malloc.

DeadMG
Objective C is the same as C here
Mark
+1  A: 

In C, once created, arrays cannot change size. For that you need pointers and malloc() and friends.

In C99 there's a new functionality called "variable length array" (VLA) which allows you to use arrays with lengths defined at run time (but fixed for the duration of the object)

while (1) {
    /* C99 only */
    int rows = 1 + rand() % 10; /* 1 to 10 */
    int cols = 1 + rand() % 10; /* 1 to 10 */
    {
       int array[rows][cols];
       /* use array, different sizes every time through the loop */
    }
}
pmg