是否可以使用calloc()一次在c中动态分配二维数组? [英] Is it possible to dynamically allocate 2-D array in c with using calloc() once?

查看:226
本文介绍了是否可以使用calloc()一次在c中动态分配二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

All the solutions I have seen online has calloc() function used twice, is it possible to do with only using it once? The below code is not printing the correct array elements

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]);
 }
}


推荐答案

自C99您可以使用指向VLA(可变长度数组)的指针:

Since C99 you can use pointers to VLAs (Variable Length Arrays):

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

这篇关于是否可以使用calloc()一次在c中动态分配二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆