views:

19

answers:

1

I'm sure I've got a basic problem in my C knowledge. I have one variable defined in the @interface:

uint * theBytes;

and then I have a method for checking the values of that array.

- (IBAction) checkNow {
 NSLog(@"now? %d %d %d", theBytes[0], theBytes[1], theBytes[2]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
 uint tryThis[3] = {72,2,244};
 theBytes = tryThis;
 [self checkNow];
}

The initial checkNow displays the values fine. If I call checkNow on a button press later, the values are totally different and strange.

I can do this with NSData quite easily, but I'd like to do it with straight arrays.

+2  A: 

You can't assign a local array to a pointer that you want to stick around after the current stack frame. You have to use dynamic memory, obtained from malloc() or a similar function. If you want to use a byte array, you're going to have to malloc(), memcpy() and free() the memory appropriately every time you want to reassign it.

For example, that would be:

- (IBAction) checkNow {
 NSLog(@"now? %d %d %d", theBytes[0], theBytes[1], theBytes[2]);
}

- (void)viewDidLoad {
 [super viewDidLoad];
 uint tryThis[3] = {72,2,244};
 theBytes = malloc(3 * sizeof(uint));
 memcpy(theBytes, tryThis, 3 * sizeof(uint));
 [self checkNow];
}

// In order not to leak, you'll also need:

- (void)dealloc {
  free(theBytes);
  [super dealloc];
}

Yes, working with C arrays is a pain. This is why it's generally avoided in every other language, even close relatives like C++ and Objective-C.

Chuck
Thanks @Chuck, that's great. I'll use NSData for now, and if I run into memory/speed problems, I'll come back to this answer later.
Yar