我试图理解这两个片段之间的区别。两者都工作得很好。
int rows = 4;
int **p = malloc(rows * sizeof(int **)); //it works without type casting
和
int**p = (int **) malloc(rows * sizeof(int*)); // using casting method.
sizeof(int**)
是什么意思?
最佳答案
分配 foo_t
的数组s,标准模式是以下之一:
foo_t *p = malloc(count * sizeof(foo_t));
foo_t *p = malloc(count * sizeof(*p));
您可以说“给我count个尺寸为s的元素”,其中尺寸为sizeof(foo_t)
或sizeof(*p)
。它们是等效的,但第二个更好,因为它避免了写入 foo_t
两次。 (这样,如果您将 foo *p
更改为 bar *p
,您就不必记得将 sizeof(foo_t)
更改为 sizeof(bar_t)
。)
因此,要分配一个 int *
的数组,替换foo_t
与 int *
,产生:
int **p = malloc(count * sizeof(int *));
int **p = malloc(count * sizeof(*p));
请注意,正确的大小是 sizeof(int *)
,不是sizeof(int **)
。两颗星太多了。您写的第一个片段 sizeof(int **)
因此,是错误的。它似乎有效,但这只是运气。
另请注意,我没有包含 (int **)
throw 。 Actor 阵容会起作用,但是it's a bad idea to cast the return value of malloc()
。强制转换是不必要的,并且可能隐藏一个微妙的错误*。请参阅linked question以获得完整的解释。
* 即,忘记 #include <stdlib.h>
.
关于c - 动态内存分配和指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54756055/