jbrennan
jbrennan

Reputation: 12003

Storing a C array of C structs in NSData

I've got a really simple C struct like so:

typedef struct {
    int tag;
    CGPoint position;
} Place;

That is, all scalar types and no pointers in the struct.

Then I've got an array of those points like so:

 Place *dynamicPlaces = calloc(numberOfPlaces, sizeof(Place));

So each element of dynamicPlaces ought to be (unless I've mixed something up… it's certainly possible with me and pointers…) a struct of type Place, initialized with all its members to 0, yeah? So far so good.

Then I'm trying to put that array in an NSData object to be sent over the network (along with the count of elements, not shown):

NSData *placesData = [NSData dataWithBytes:dynamicPlaces length:(sizeof(Place) * numberOfPlaces)];

I'm passing it the array directly, because if memory serves, the pointer dynamicPlaces is really pointing to the first struct element of the array, and then I tell it how many elements there are via length. I think this is good.

Finally, on the other side I do this when decoding my object.

[receivedData getBytes:receivedDynamicPlacesArrayPointer length:[receivedData length]];

But I get an EXC_BAD_ACCESS on that line and I can't quite figure out why. As far as I can tell by the documentation, this ought to be storing the bytes from the NSData into a copied location in memory, and point to that blob with receivedDynamicPlacesArrayPointer.

It's entirely possible I've made a mistake doing this, pointers trip me up, even though I think I understand them. Any help would be greatly appreciated.

Upvotes: 3

Views: 1550

Answers (1)

Ken Aspeslagh
Ken Aspeslagh

Reputation: 11594

getBytes:length: docs say: "Copies a number of bytes from the start of the receiver's data into a given buffer."

So you will need to first allocate memory for receivedDynamicPlacesArrayPointer yourself. Did you do that?

In other words, you'd do like:

 Place* receivedDynamicPlacesArrayPointer = (Place*)malloc([receivedData length]);

Upvotes: 3

Related Questions