In Objective-C, I declare a C array like this:
int length = 10;
int a[length];
This does not cause any errors in Xcode but other compliers like Visual Studio.
Please tell me how it works. Should I use it or use malloc/calloc instead?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Variable length arrays were introduced in C99. Microsoft’s current compiler (VC2010) doesn’t support C99 (or at least the VLA part of it) as far as I’m aware.
You can use
mallocto do the same sort of thing, you just have to remember tofreeit when you’re done.Something like:
You can probably also use
allocawhich is similar to VLAs in that it allocates space on the stack for variables memory blocks.But you have to be careful. While
allocagives you automatic de-allocation on function exit, the stack is usually a smaller resource than themallocheap and, if you exhaust the heap, it gives you back NULL. If you blow out your stack, that will probably manifest itself as a crash.alloca(n)is probably acceptable for small enough values ofn.