我正试图了解这两个摘要之间的区别。他们两个都工作正常。
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**)
是什么意思?
答案 0 :(得分:1)
要分配foo_t
的数组,标准模式是以下之一:
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 **)
演员表。强制转换将起作用,但是it's a bad idea to cast the return value of malloc()
。强制转换是不必要的,并且可能隐藏细微的错误 * 。有关完整说明,请参见linked question。
*即,忘记了#include <stdlib.h>
。