1

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Objective C is the same as C here
1

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 */
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.