简体   繁体   中英

Accessing struct array of unsigned ints

I have a struct that has space for unsigned ints:

typedef struct {
    unsigned int *arr;
} Contents;

When I allocate memory:

Contents *Allocator()
{
    Contents *cnt = malloc(sizeof(Contents));
    cnt->arr = calloc(1, sizeof(unsigned int));
}

I later retrieve it by dereferencing it by passing in a pointer to Contents and doing:

void SomeFunction(Contents *cnt)
{
   unsigned int * arr = cnt->arr;
   arr[0] >>= 1; // In the future 0 will be replaced by a loop over the array items
   cnt->arr = arr;
 }

Once I exit out of the function, cnt->arr becomes empty. Do I have to do a memcpy? Am I not understanding how the struct is laid out? As I understand

cnt->arr = (*cnt).arr

Thanks!

The problem is that you're doing unsigned int *arr = cnt->arr , which declares an unsigned int pointer and makes it point to cnt->arr. Once you modify the array, you then attempt to re-set the array - but by re-assigning pointers, you haven't changed the contents of the array; you've only changed the pointers . Thus, your cnt->arr = arr line doesn't actually change anything. Then, "unsigned int *arr" runs out of scope, and thus the pointer is destroyed, leaving you with unrecoverable data.

You'll need to copy the array somewhere temporary instead, and do your operations on that array instead, and then copy it back, OR (the easier method) just use your arr pointer and don't then try cnt->arr = arr - this effect will have been achieved anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM