How Can i declare dynamic array ? for example int k=5; i want to have an array like below
int myArray[k]
How Can i declare dynamic array ? for example int k=5; i want to have an array like below
int myArray[k]
if i read the question right.. (unlikely at this point)
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:k];
In Objective-C, the standard way to do this is to use the NSMutableArray
class. This is a container that can hold any object (note that int
is not an object! You'll have to wrap your integers in NSNumber
.) Quick example:
NSMutableArray* someIntegers = [[NSMutableArray alloc] initWithCapacity:1];
[someIntegers addObject:[NSNumber numberWithInt:2]]; //I've added one thing to my array.
[someIntegers addObject:[NSNumber numberWithInt:4]];
//See how I can put more objects in that my capacity allows? The array will automatically expand if needed.
//The array now contains 2 (at index 0) and 4 (at index 1)
int secondInteger = [[someIntegers objectAtIndex:1] intValue];
//Retrieving my second int. -intValue is required because I stored it as NSNumber,
//which was necessary, because NSMutableArray holds objects, not primitives.