Divide large malloc-block into smaller “partitions”

Is there a way to use poiter arithmetic on a large malloc block, so you can assign multiple structs or primitive data types to that area already allocated? I'm writing something like this but it isnt working (trying to assign 200 structs to a 15000byte malloc area):

char *primDataPtr = NULL;

typedef struct Metadata METADATA;

struct Metadata {
};/*struct Metadata*/


primDataPtr = (void*)(malloc(15000));
if(primDataPtr == NULL) {       

char *tempPtr = primDataPtr;
int x;
for(x=0;x<200;x++) {
        METADATA *md = (void*)(primDataPtr + (sizeof(METADATA) * x));
}//end x -for
13.10.2009 15:42:26
You're thinking about this the wrong way. Read up on "pointer arithmetic" and stop think about primDataPtr being a large block of bytes (chars). For example, using pointer arithmetic, if you had a pointer to METADATA, then (pointer + 1) would point to the next block of METADATA, not the next byte. That's key to writing a workable solution. Read up on the wonderful world of pointer arithmetic... and proper casting.
Robert Cartaino 13.10.2009 17:46:30

The only thing I can see is that:

METADATA *md = (void*)(primDataPtr + (sizeof(METADATA) * x));

should be:

METADATA *md = (METADATA *)(primDataPtr + (sizeof(METADATA) * x));

I think?

PS: your malloc could also just allocation 200 * sizeof(METADATA).

13.10.2009 15:56:24

In C, the syntax for a pointer to something is just like the syntax for an array of something. You just need to be careful with the index ranges:

#define ARRAY_SIZE_IN_BYTES (15000)

void *primDataPtr = (void*) malloc(ARRAY_SIZE_IN_BYTES);

METADATA *md = (METADATA *)primDataPtr;
for (x=0; x<(ARRAY_SIZE_IN_BYTES/sizeof(METADATA)); x++) {
13.10.2009 15:59:50