0

As an iOS programmer I sometimes delve into C to achieve faster results (well actually for fun) and I'm struggling to modify a C-array's values inside a function call. Although I think this answer may help (Modifying a array in a function in C), I don't know where to begin in implementing it.

Currently I have:

[object.guestlists enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {

   NSObject *someNSObject = [NSObject new];

   NSInteger array[3] = {totalIncomingMales,totalIncomingFemales, 
                        totalIncomingGuestsCount};

   [self callMethod:object withCArray:cArray];

}];


- (void) callMethod:(NSObject*) object withCArray:(NSInteger*) cArray {

    // do something with that object

    NSInteger   totalIncomingMales = cArray[0],
                totalIncomingFemales = cArray[1],
                totalIncomingGuestsCount = cArray[2];

    // modify these integers internally so that the C-array passed in is also modified

}

Obviously this passes a pointer and therefore doesn't modify the value. I tried replacing the NSinteger * with NSInteger ** and making, e.g. totalIncomingMales = * cArray[0], but alas I wasn't able to pass the c-array as a parameter (even with an ampersand).

Some useful material and potentially a solution to this would be much appreciated!

4
  • You use ** only with NSObjects and its subclass. NSInteger is just a primitive int. I believe * and/ & should work. Commented Dec 5, 2014 at 13:29
  • Where does arrayOfIntegers come from? Commented Dec 5, 2014 at 13:32
  • Sorry, have edited. I tried using ampersand, I think. Let me try again Commented Dec 5, 2014 at 13:38
  • Yer, just using the ampersand gives me a compiler warning NSInteger(*)[3] to NSInteger * (aka int *) Commented Dec 5, 2014 at 13:40

1 Answer 1

1

Not sure if I understand your question, but it seems to be trivial one:

- (void) callMethod:(NSObject*) object withCArray:(NSInteger*) cArray {
     // modify these integers internally so that the C-array passed in is also modified
     cArray[0] = 10;
     cArray[1] = 20;
     cArray[2] = 30;
}


- (void) myMethod:(NSString *) myConstString array: (NSArray *) myArray
{
    NSInteger array[3] = {1,2,3};
    NSLog(@"%ld %ld %ld", (long)array[0],(long)array[1],(long)array[2]);
    [self callMethod:nil withCArray:array];
    NSLog(@"%ld %ld %ld", (long)array[0],(long)array[1],(long)array[2]);
}

result will be: 1,2,3 after 10,20,30. No pointer trickery needed, because you are telling it is NSInteger so compiler does it for you.

Sign up to request clarification or add additional context in comments.

1 Comment

That's it. It was a slip on my part and I shouldn't have been assigning them to new variables. So dum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.