Initiate and write an array in objective-c

In my h file, I declare var, which should later be an array:

@interface myClass : CCNode {
  CGPoint *mVertices;
}

@end

In my init method:

mVertices = malloc(size * size * sizeof(CGPoint));

mVertices[0][0] = ccp(0,0);

In this last line, I get the error The subscript value is neither an array nor a pointer . Why am I getting this error and how to solve this problem?

+3
source share
2 answers

Your array is not two-dimensional. This is just a list of vertices.
If you want to allocate space for a dynamic two-dimensional array in C, you can do:

CGPoint** mVertices;
NSInteger nrows = 10;
NSInteger ncolumns = 5;
mVertices = calloc(sizeof(CGPoint*), nrows);
if(mVertices == NULL){NSLog(@"Not enough memory to allocate array.");}
for(NSUInteger i = 0; i < nrows; i++)
{
    mVertices[i] = calloc(sizeof(CGPoint), ncolumns);
    if(mVertices[i] == NULL){NSLog(@"Not enough memory to allocate array.");}
}
mVertices[0][5] = CGPointMake(12.0, 24.0);
mVertices[1][5] = CGPointMake(22.0, 24.0);
mVertices[2][5] = CGPointMake(32.0, 24.0);    
mVertices[2][1] = CGPointMake(32.0, 24.0);
for(NSUInteger i = 0; i < nrows; i++)
{
    for (int k = 0; k < ncolumns; k++) 
    {
        NSLog(@"Point %@", NSStringFromPoint(NSPointFromCGPoint(mVertices[i][k])));
    }
}

I used callocinstead mallocto get CGPoints initialized with 0.0.

+2
source

mVertices - , , ( ).

(Objective) -C , , , , .

:

mVertices[(row * size) + column] = ccp(row, column);

:

#define VERTICE_ACCESS(row,colum) mVertices[(row * size) + column]
+3

All Articles