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.
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 tomalloc(),memcpy()andfree()the memory appropriately every time you want to reassign it.For example, that would be:
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.