Re: Accessors for 2D Arrays?
Re: Accessors for 2D Arrays?
- Subject: Re: Accessors for 2D Arrays?
- From: Greg Herlihy <email@hidden>
- Date: Tue, 01 Nov 2005 20:49:07 -0800
- Thread-topic: Accessors for 2D Arrays?
On 11/1/05 6:42 PM, "jz" <email@hidden> wrote:
>
> #import <Cocoa/Cocoa.h>
> int gM[4][4] = {{0, 0, 0, 0,}, {0, 0, 0, 0,}, {0, 0, 0, 0,}, {0, 0, 0, 0,}};
> @interface MyController: NSObject {
> - (int)gM[4][4];
> - (void)setGM[4][4]: (int)aGM[4][4];
> }
> @implementation MyController
>
> - (int)gM[4][4]
> {
> return gM[4][4];
> }
In Objective-C the type of the parameter is declared within a pair of
parentheses. Furthermore, it's not possible to return an array by value in
Objective C. So returning a pointer to a 4 by 4 int array (suitably
typedef-ed for clarity) would be one possible solution:
typedef int GMArray[4][4];
@interface MyController: NSObject {
-(GMArray*)gM;
-(void)setGM:(GMArray)aGM;
-(GMArray *)gM
{
return &gM;
}
> - (void)setGM[4][4]:(int)aGM[4][4]
> {
> gM[4][4] = aGM[4][4];
> }
> The above accessors don't work.
The range of valid indexes for a 4 by 4 array are 0-3. Therefore returning
the element at [4][4] - as this routine is attempting - is an out-of-bounds
memory access. So it's a good thing this syntax did not work.
-(void)setGM:(GMArray)aGM
{
// next line is an out-of-bounds memory access
// gM[4][4] = aGM[4][4];
// use memmove to copy the array
memmove(gM, aGM, sizeof(gM));
}
> How to write accessors for a global array to replace one item and retain value
> of other items?
>
> I also tried: [gM[4][4] replaceObjectAtIndex: 1,1 withObject: [NSNumber
> numberWithInt: 99] ]; but the compiler gives me an error "invalid integer gM"
gM is just an ordinary C multidimensional array. Simple assignment to the
properly-indexed element is all that is needed to change that element, while
iterating and assigning - or calling memmove - can copy multiple elements
from another array of the same size into the gM array.
Greg
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden