Quote:
Originally Posted by benoitr007
Hello,
I know it's no big deal, but I was wondering... Why do we have to initialize arrays with a size, for example it won't let me do this:
Code:
NSString *category[];
But it lets me do this:
Code:
NSString *category[0];
However, I have no idea what the size of the array actually changes, because even if I put 0 it works and I can save values such as:
category[0] = @"Hello";
category[1] = @"How are you";
category[2] = @"Blah blah";
and retrieve them correctly after. What am I missing? Thank you very much!
|
Using the [] bracket notation is the C-style syntax, which causes (in this case) a fixed-size array of NSString * instances to be allocated. In order for the compiler to allocate the correct amount of storage for the data, it has to know the size of the array, which is why the value is required in between the square brackets.
If you need a variable sized array, just use NSMutableArray.
Also, the example code that you provided where you access elements 0, 1 and 2 or your array is stomping memory outside of the array. The code may appear to work correctly, but since the compiler hasn't actually allocated the correct amount of space for the array, you're actually writing over memory that is beyond the bounds of whatever space has been allocated.