views:

119

answers:

2

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) {  
 exit(1);
}

char *tempPtr = primDataPtr;
int x;
for(x=0;x<200;x++) {
        METADATA *md = (void*)(primDataPtr + (sizeof(METADATA) * x));
}//end x -for
+1  A: 

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).

Douglas Leeder
A: 

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);
assert(primDataPtr);

METADATA *md = (METADATA *)primDataPtr;
for (x=0; x<(ARRAY_SIZE_IN_BYTES/sizeof(METADATA)); x++) {
    do_something_with(md[x]);
}
ndim