I’ve been programming for a while in objective-c, but I’ve unfortunately never delved very deeply into C and memory pointers, although I do have a rudimentary understanding of them. I’m working with an array of CLLocationCoordinate2D structures, and I’m trying to figure out how to append to the array. First of all, I get the
NSString *aString; //a bunch of coordinates
CLLocationCoordinate2d *coordinates;
int length;
doSomethingCool(aString, &coordinates, &length);
after I do something cool, I want to preserve it in a class variable. If I simply do something like
points = newPoints
points contains the appropriate contents. However, if I try to do something like this:
points = malloc(sizeof(CLLocationCoordinate2D) * length);
points[0] = *newPoints;
points ends up with contents different from newPoints.
Ultimately my goal is to be able to append to points based on length, but I’m not going to be able to do that if I can’t get the above code to work. What am I doing wrong?
Your code simply copies the first value of
newPointsinto the first value ofpoints(*newPointsis equivalent tonewPoints[0]).One situation is to make a new array, copy all values, switch the arrays, and free() the old one. For example:
You can also use
realloc– its behavior is similar to the above (though it can fail!), but at times may be more efficient.Note that you simply can’t change the underlying pointer’s size in a safe and portable fashion. You will need to update your instance (“class”) variable with the new pointer.