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?

有帮助吗?

解决方案

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 to free it when you're done.

Something like:

int length = 10;
int *a = malloc (length * sizeof(int));
if (a == NULL) {
    doSomethingIntelligentSinceNoMemoryLeft();
} else {
    useToHeartsContent (a[0], "thru", a[9]);
    free (a);
}

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 the malloc 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 of n.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top