如果我采用下面的 2 个片段代码(它们是等效的):
double ***x;
x = malloc(N * sizeof(*x));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(**x));
和
double ***x;
x = malloc(N * sizeof(double*));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(double**));
上面第一个的语法应该是:
double ***x;
x = malloc(N * sizeof(*x));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(*x));
我的意思是,对于 x
、x[i]
和 x[i][j]
malloc
分配时,语法仍为“sizeof(*x)
”,对吗?
??
第二个应该是:
double ***x;
x = malloc(N * sizeof(double**));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(double*));
??
我从 this link 看到了这个语法
It is safer becuse you don't have to mention the type name twice and don't have to build the proper spelling for "dereferenced" version of the type. For example, you don't have to "count the stars" in
int *****p = malloc(100 * sizeof *p);
Compare that to the type-based sizeof in
int *****p = malloc(100 * sizeof(int ****));
where you have too make sure you used the right number of * under sizeof.
问候
更新1:
我在语法下方得到了一个答案作为模式:
p = malloc(N * sizeof *p);
是否有空格(N
、sizeof
和 *p
之间)以及 sizeof *p
中缺少括号> (而不是 sizeof(*p)
)必须严格应用于此分配的语法?
在我的代码中,我做了:
/* Arrays */
double** x;
double** x0;
/* Allocation of 2D arrays */
x = malloc(size_tot_y*sizeof(*x));
x0 = malloc(size_tot_y*sizeof(*x0));
for(i=0;i<=size_tot_y-1;i++)
{
x[i] = malloc(size_tot_x*sizeof(**x));
x0[i] = malloc(size_tot_x*sizeof(**x0));
}
如您所见,我在 sizeof
中使用了括号,并且在 size_tot_*
、sizeof
和 * 之间没有使用空格p
。
我的语法是否会改变任何内容以遵守上述模式?
这可能是一个愚蠢的问题,但我想得到确认。
谢谢
最佳答案
模式是:
p = malloc(N * sizeof *p);
在这两种情况下将 p
替换为相同的内容。例如:
x[i] = malloc(N * sizeof *x[i]);
有时,人们会使用 **x
表示 *x[ 的知识,将
、*x[i]
缩写为 **x
0]x[0]
和 x[i]
具有相同的大小,因为数组的所有元素必须具有相同的类型,因此也相同尺寸。
但是,如果您对这一切都没有信心,那么您可以坚持基本模式并使用 *x[i]
。
关于c - 正确的分配语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971837/