访问无符号整数的结构数组
我有一个具有用于无符号整数的空间的结构:
typedef struct {
unsigned int *arr;
} Contents;
当我分配内存时:
Contents *Allocator()
{
Contents *cnt = malloc(sizeof(Contents));
cnt->arr = calloc(1, sizeof(unsigned int));
}
我稍后通过传入一个指向 Contents 的指针来取消引用它并执行以下操作来检索它:
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;
}
一旦我退出该函数,cnt->arr 就会变为空。我必须做 memcpy 吗?我不明白结构是如何布局的吗?据我了解
cnt->arr = (*cnt).arr
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您正在执行
unsigned int *arr = cnt->arr
,它声明了一个 unsigned int 指针并使其指向 cnt->arr。修改数组后,您将尝试重新设置数组 - 但通过重新分配指针,您并没有更改数组的内容;您仅更改了指针。因此,您的cnt->arr = arr
行实际上并没有改变任何东西。然后,“unsigned int *arr”超出范围,因此指针被破坏,留下无法恢复的数据。您需要将数组复制到临时的某个地方,然后对该数组执行操作,然后将其复制回来,或者(更简单的方法)只需使用您的
arr
指针和 don 't然后尝试cnt->arr = arr
- 无论如何都会达到这个效果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, yourcnt->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 trycnt->arr = arr
- this effect will have been achieved anyway