1

How can I declare dynamic array? For example:

int k=5;

I want to have an array like below:

int myArray[k];
thkala
  • 84,049
  • 23
  • 157
  • 201

5 Answers5

8

if i read the question right.. (unlikely at this point)

NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:k];
Chuck
  • 234,037
  • 30
  • 302
  • 389
Jesse Naugher
  • 9,780
  • 1
  • 41
  • 56
8

Sometimes true arrays (not NSArray) are really needed. See for example indexPathWithIndexes:length: in NSIndexPath, it take array of uintegers as parameter. For array allocation you should use the following approach:

    NSUInteger *arr = (NSUInteger*)malloc(elementsCount * sizeof(NSUInteger) );
    arr[0] = 100;
    free(arr);
Sneg
  • 1,039
  • 1
  • 11
  • 15
7

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 than 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 an item. -intValue is needed because I stored it as NSNumber,
//which was necessary, because NSMutableArray holds objects, not primitives.
andyvn22
  • 14,696
  • 1
  • 52
  • 74
3

Well in my book it's ok to use VLAs in Objective-C.

So something like

int foo = 10;
int bar[foo];

is allowed. Of course this is not a dynamic array as in automatically adjusting its size. But if you only need a native array on the stack that's fine.

1

You can use Objetive-C++.

First rename your class like this: MyClass.mm the ".mm" extension tells Xcode that this clas is a Objetive-C++ class, not a Objetive-C class.

then you can use dynamics C++ arrays like this:

int *pixels = new int[self.view.size.width];

for (int offset = 0; offset = self.view.size.width; offset++) {
    pixeles[offset] = rawData[offset];
}

then you can pass "pixels" in a method:

Scan *myScan = [[Scan alloc] initWhithArray:pixels];

the method "initWithScan" is declared like this:

-(id)initWithArray:int[]pixels;

the "initWithScan" implementation is like this:

-(id)initWithScan:int[]pixels {
    if (self = [super init]) {
        for (int i = 0; i < self.myView.size.width; i++) {
            NSLog(@"Pixel: %i", pixels[i];
        }
    }
    return self;
}

I hoppe this was useful.

Menio
  • 61
  • 7