c - Accessing struct array of unsigned ints -
i have struct has space unsigned ints:
typedef struct { unsigned int *arr; } contents;
when allocate memory:
contents *allocator() { contents *cnt = malloc(sizeof(contents)); cnt->arr = calloc(1, sizeof(unsigned int)); }
i later retrieve dereferencing passing in pointer contents , doing:
void somefunction(contents *cnt) { unsigned int * arr = cnt->arr; arr[0] >>= 1; // in future 0 replaced loop on array items cnt->arr = arr; }
once exit out of function, cnt->arr becomes empty. have memcpy? not understanding how struct laid out? understand
cnt->arr = (*cnt).arr
thanks!
the problem you're doing unsigned int *arr = cnt->arr
, declares unsigned int pointer , makes point cnt->arr. once modify array, attempt re-set array - re-assigning pointers, haven't changed contents of array; you've changed pointers. thus, cnt->arr = arr
line doesn't change anything. then, "unsigned int *arr" runs out of scope, , pointer destroyed, leaving unrecoverable data.
you'll need copy array somewhere temporary instead, , operations on array instead, , copy back, or (the easier method) use arr
pointer , don't try cnt->arr = arr
- effect have been achieved anyway
Comments
Post a Comment