【问题标题】:Is it possible to dynamically allocate 2-D array in c with using calloc() once?是否可以使用 calloc() 一次在 c 中动态分配二维数组?
【发布时间】:2019-03-10 17:35:12
【问题描述】:

我在网上看到的所有解决方案都使用了两次 calloc() 函数,是否可以只使用一次? 下面的代码没有打印正确的数组元素

int **ptr;

//To allocate the memory 
ptr=(int **)calloc(n,sizeof(int)*m);

printf("\nEnter the elments: ");

//To access the memory
for(i=0;i<n;i++)
{  
 for(j=0;j<m;j++)
 {  
  scanf("%d",ptr[i][j]);
 }
}

【问题讨论】:

标签: c multidimensional-array dynamic


【解决方案1】:

从 C99 开始,您可以使用指向 VLA(可变长度数组)的指针:

int n, m;

scanf("%d %d", &n, &m);

int (*ptr)[m] = malloc(sizeof(int [n][m]));

for (i = 0; i < n; i++)
{  
    for (j = 0; j < m; j++)
    {  
        scanf("%d", &ptr[i][j]); // Notice the address of operator (&) for scanf
    }
}
free(ptr); // Call free only once

【讨论】:

  • 如果在运行时定义 m,n 会怎样?
  • 这就是 VLA 的目的,您可以在运行时设置它,进行编辑以反映这一点。
  • 因为 C11 VLA 是可选的 ;)
  • 值得注意的是,这段代码实际上并没有使用 VLA,而是一个指向 VLA 的指针。 C11 委员会很困惑,没有看到指向 VLA 的指针的好处,这在现代 C 编程中很重要。与实际分配的 VLA 不同,后者的用处要小得多。
【解决方案2】:

如果只是为了尽量减少对内存分配函数的调用次数,您可以创建这样的锯齿状数组:

#include <stdlib.h>
#include <stdio.h>

int ** alloc_jagged_2d_array_of_int(size_t n, size_t m)
{
  int ** result = NULL;
  size_t t = 0;

  t += n * sizeof *result;
  t += n*m * sizeof **result;

  result = calloc(1, t);
  if (NULL != result)
  {
    for (size_t i = 0; i < n; ++i)
    {
      result[i] = ((int*) (result + n)) + i*m;
    }
  }

  return result;
}

像这样使用它:

#include <stdlib.h>
#include <stdio.h>

int ** alloc_jagged_2d_array_of_int(size_t, size_t);

int main(void)
{
  int result = EXIT_SUCCESS;

  int ** p = alloc_jagged_2d_array_of_int(2, 3);
  if (NULL == p)
  {
    perror("alloc_jagged_2d_array_of_int() failed");
    result = EXIT_FAILURE;
  }
  else
  {
    for (size_t i = 0; i < 2; ++i)
    {
      for (size_t j = 0; j < 3; ++j)
      {
        p[i][j] = (int) (i*j);
      }
    }
  }

  /* Clean up. */

  free(p);

  return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2011-10-01
    • 2021-02-03
    • 2017-09-28
    • 1970-01-01
    • 2015-09-17
    相关资源
    最近更新 更多