开发者

Using sizeof for a pointer to a pointer to an array of 2 floats

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. Sh开发者_运维百科ould 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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜