动态内存分配和指针?

Dynamic memory allocation and pointers?

我试图了解这两个片段之间的区别。他们两个都很好。

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 的数组,标准模式是以下之一:

foo_t *p = malloc(count * sizeof(foo_t));
foo_t *p = malloc(count * sizeof(*p));

您可以说 "give me count items of size 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(). The cast is unnecessary and could hide a subtle error*. See the linked question 需要完整的解释。


* 即忘记 #include <stdlib.h>.