访问无符号整数的结构数组

发布于 2024-11-04 08:47:36 字数 666 浏览 0 评论 0原文

我有一个具有用于无符号整数的空间的结构:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我只土不豪 2024-11-11 08:47:36

问题是您正在执行 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, 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文