c - 正确的分配语法

标签 c pointers sizeof

如果我采用下面的 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));

我的意思是,对于 xx[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);

是否有空格(Nsizeof*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/

相关文章:

c - 在堆栈中查找最小值,时间复杂度为 O(1)

c - 在C语言中使用clock()来测量时间

c++ - 通过引用传递是作为指针传递的特例吗?

c# - 检索结构体的 [StructLayout] 属性

c++ - 为什么这个结构需要一个大小值?

c++ - 为什么 64 位和 32 位系统中的 Struct 填充相同?

c - 获取关系运算符和按位右移作为命令行参数

c - C语言中的变量加法

c - 赋值从 int 中生成指针 w/out a cast

c++ - 为什么有人将对象定义为指针?