i have two Objective-C classes, say ParentLayer and ChildLayer. in my child instance, i want to access a C-Array in my parent instance. so i have something like this in my cocos2d code:
#define kNumOfElements 10
@implementation ParentLayer{
int array[kNumOfElements];
}
-(id)init{
//...
for(int i=0;i<kNumOfElements;i++){
array[i] = i;
}
[self addChild:childLayer];
[childLayer initializeValues];
//...
}
-(int *)getArray{
return array;
}
@end
//meanwhile in my child layer...
//...
-(void)initializeValues{
int *arr = [(ParentLayer *)[self parent] getArray];
//NSLog(@"%d",arr[0]); <------- this gives you bad exec access point, and looks like it's 0x00 for memory address
}
//...
- what’s the proper way to do this?
- maybe i dont understand the right memory management behind C Arrays.
i was under the impression that C Arrays didn’t need to be allocated,
and that they could be passed by value, on the stack? - also, shouldn’t my parent instance still be around? i thought if i
put a C Array as an ivar of my parent, it shouldn’t get destroyed
any help is appreciated. thanks!
Ideally, you should never pass a C-style array pointer outside of the object that owns it. You open yourself up to all sorts of problems if a piece of code tries to use the array after the object is deallocated, or writes past the end, or something else. It is easier to guarantee that none of this happens if you can make sure the reference never leaves the object’s source file.
It is not that simple.
A C-style array is just a memory address. That’s it. It doesn’t carry around the other useful information that an object might, such as number of elements, retain count.
If you declare an array like this:
Then the memory is allocated in either the stack or the heap, depending on where you put the declaration. If it’s a local variable inside a function or method, it’s on the stack. If it’s in global scope or a member variable of an object, it’s on the heap.
Furthermore, if it’s an instance variable, you’re actually setting aside 100 ints worth of memory inside the block of memory allocated to hold the object. It isn’t a separate thing.
Since
arrayis just a memory address, you are basically passing it around by reference. Technically, you are passing the address by value, but any changes you make to the memory will be seen by anyone looking at the same address, so it acts like pass by reference.The way you have coded it, that array will be valid as long as the parent object is around. Once the parent gets deallocated, that memory could be reclaimed. Since the
arrayvariable is just a memory address, however, you have no way of knowing whether the data it points to is valid or not. This is the danger of using C-style arrays rather than objects.Since the last line is giving you NULL (0) address, my guess is that
[self parent]is nil. That would put a 0 inarr; when you try to dereference NULL, you will get an exception.