2

I'm trying to write an Objective C class which draws an OpenGL polygon. I've managed to do this using an NSMutableArray to store my vertex coordinates. However this seems a bit inefficient because each time an object is drawn it's necessary to loop over the array to convert the NSMutableArray to a ccVertex2F [] array.

What I want to do is have a ccVertex2F array as an instance variable. Then on initialisation set the size to the number of points. This however throws an error because the size of my array is always zero.

I'm experienced at programming Java but totally new to C and memory management. So far this is what I have:

@interface PolygonNode : CCNode {
    ccVertex2F *  _glPoints ;
}

@property (nonatomic, readwrite) ccVertex2F * glPoints ;
@end

My understanding of this is that I'm creating an instance variable which is a pointer to a ccVertex2F.

In my init method I have the following:

    ccVertex2F sizedGlPoints [numberOfPoints * sizeof(ccVertex2F)];
    _glPoints = &sizedGlPoints;

The aim of this was to make the instance variable point to my new correctly sized array. However, when I print the sizes after this code _glPoints size doesn't change.

The core of what I want to do is to be able to choose the size of my array when I initialise the class so that I'm not wasting memory.

2 Answers 2

2

You can use malloc to allocate memory for the array:

ccVertext2F *newMemory = malloc(numberOfPoints * sizeof(ccVertex2F));
if (newMemory == NULL) {
    // Handle error
}
_glPoints = newMemory;

Just remember to free it when you're done (in -dealloc or before you assign it again):

free(_glPoints);
Sign up to request clarification or add additional context in comments.

Comments

0

If you're trying to allocate using pure C, you use malloc or calloc to allocate, and free to deallocate.

So

ccVertex2F sizedGlPoints [numberOfPoints * sizeof(ccVertex2F)];   
_glPoints = &sizedGlPoints;

would become

_glPoints = (ccVertex2F *) calloc( numberOfPoints, sizeof( ccVertex2F );

If ccVertex2F were an ObjectiveC class, you would use

[ ccVertex2F alloc ] 

to do the allocation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.