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?
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?
Copyright © 2021 Jogjafile Inc.
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
malloc
to do the same sort of thing, you just have to remember tofree
it when you're done.Something like:
You can probably also use
alloca
which is similar to VLAs in that it allocates space on the stack for variables memory blocks.But you have to be careful. While
alloca
gives you automatic de-allocation on function exit, the stack is usually a smaller resource than themalloc
heap 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
.