使用 sizeof 作为指向 2 个浮点数组的指针

发布于 2024-10-09 17:55:03 字数 608 浏览 4 评论 0原文

我已经声明了这个变量:

float (**explosions)[4];

这将指向一个内存块,该内存块由指向具有 4 个浮点数的浮点数组的内存块的指针组成。

当制作指向浮点数组内存块的指针内存块时,我在这里放什么。我应该只使用 void 指针吗?这将是一种选择,但不是一个好的选择。

explosions = realloc(explosions,sizeof(What goes here? It will be the size of a pointer to an array of 4 floats) * explosion_number);

当为数组创建内存块时,我想这是否可以?

explosions[explosion_number] = malloc(sizeof(float) * 64);

即使用 4 个元素创建 16 个浮点数组。我需要在内存中保留 16 个这样的数组的原因是这样我可以删除冗余内存,这样我就可以将指向这些数组的指针设置为 NULL,这样我就知道这些数组在冗余后何时被释放,并且不需要更多处理。以防万一你想知道。

感谢您的帮助。

I've declared this variable:

float (**explosions)[4];

This will point to a memory block of pointers to memory blocks for float arrays with 4 floats.

When making the memory block of pointers to memory blocks of float arrays what do I put here. Should I just use void pointers? That would be an option but not a nice one.

explosions = realloc(explosions,sizeof(What goes here? It will be the size of a pointer to an array of 4 floats) * explosion_number);

When creating the memory block for the arrays I guess this if fine?

explosions[explosion_number] = malloc(sizeof(float) * 64);

That's to make 16 of the float arrays with 4 elements. The reason I need to have 16 of these arrays in memory is so I can remove redundant memory and so I can make the pointer to these arrays NULL so I know when the arrays are freed after being redundant and no more processing is needed. Just in case you were wondering.

Thank you for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

挽容 2024-10-16 17:55:03

sizeof 可以使用括号内的类型或表达式。当您执行 sizeof 时,仅检查表达式的类型,但不会对其进行求值,因此取消引用空指针等不会出现问题。

这意味着您可以像这样编写 reallocmalloc 调用:

explosions = realloc(explosions, sizeof(*explosions) * explosion_number);
explosions[explosion_number-1] = malloc(16 * sizeof(**explosions));
  // -1 because explosions array runs from 0 to (explosion_number-1)

sizeof can work with either a type within parentheses or with an expression. When you do sizeof <expression>, then the expression is only checked for its type but it is not evaluated, so there can be no problems with dereferencing null pointers or the like.

This means you can write the realloc and malloc calls like this:

explosions = realloc(explosions, sizeof(*explosions) * explosion_number);
explosions[explosion_number-1] = malloc(16 * sizeof(**explosions));
  // -1 because explosions array runs from 0 to (explosion_number-1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文