I am a bit of a beginner to OOP so this may be a silly question!
I would like to use a multidimensional CArray as an instance variable in an objective-c class, and would also like to be able to specify it’s size during runtime, during the objects initialisation method:
@interface ArrayClass : NSObject {
int array[][];
}
-(id)initWithSizeX:(int)sizeX sizeY:(int)sizeY;
@end
This produces the error “Instance variable ‘array’ has unknown size.”
I can only seem to make use of the array if I declare it as having an initial size, say [20][20] for example – But that of course defeats the point because I want it to be decided at runtime!
My guess that is this is necessary as the objects memory footprint needs to be known up front?
Does anybody know if what I am trying to this is possible at all? Are there any workarounds that would allow me to size the array at runtime? Or am I going about this in completely the wrong way?
I know there are a lot of topics about multi-dimensional arrays, but I cannot seem to find anything that answers my question!
Since you’re working in Objective-C, you might consider using
NSArray(orNSMutableArraydepending on what you plan on doing with the array). This will let you send it Objective-C messages and get a lot more functionality “for free” due to it being an object, not just a chunk of memory (as an array is in C). Also, if you’re using ARC or garbage collection, it will get memory managed for you.But if you know you want to use a C array (which is totally valid), you’ll need to
mallocit (andfreeit when you’re done with it) in your code just like you would normally in C. (You can only get around this when you create a static array of a defined size at compile time, as you noted.)EDIT: As @Mahesh pointed out in the comments, you’ll want to declare your
arrayvariable asint **array;instead of
int[][] array;.Take a look here if you need more help with this!