首页 文章

如何获得双指针指向的2D数组的大小?

提问于
浏览
4

我试图从指向数组的双指针获取2D数组的行数和列数 .

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

void get_details(int **a)
{
 int row =  ???     // how get no. of rows
 int column = ???  //  how get no. of columns
 printf("\n\n%d - %d", row,column);
}

上面的功能需要打印大小的细节,哪里出错了 .

int main(int argc, char *argv[])
{
 int n = atoi(argv[1]),i,j;
 int **a =(int **)malloc(n*sizeof(int *)); // using a double pointer
 for(i=0;i<n;i++)
   a[i] = (int *)malloc(n*sizeof(int));
 printf("\nEnter %d Elements",n*n);
 for(i=0;i<n;i++)
  for(j=0;j<n;j++)
  {
   printf("\nEnter Element %dx%d : ",i,j);
   scanf("%d",&a[i][j]);
  }
 get_details(a);
 return 0;
 }

我正在使用malloc来创建数组 .


如果我使用这样的东西怎么办?

column = sizeof(a)/ sizeof(int)?

2 回答

  • 7

    C不反思 .

    指针不存储任何元数据以指示它们指向的区域的大小;如果只有指针,那么就没有(可移植的)方法来检索数组中的行数或列数 .

    您将需要将该信息与指针一起传递,或者您需要在数组本身中使用sentinel值(类似于C字符串如何使用0终止符,尽管这只会给出字符串的逻辑大小,可能小于它占据的阵列的物理尺寸) .

    The Development of the C Programming Language中,Dennis Ritchie解释说他希望像数组和结构这样的聚合类型不仅代表抽象类型,而且代表占用内存或磁盘空间的位集合;因此,该类型中没有元数据 . 那个's information you'有望追踪自己 .

  • 3
    void get_details(int **a)
    {
     int row =  ???     // how get no. of rows
     int column = ???  //  how get no. of columns
     printf("\n\n%d - %d", row,column);
    }
    

    我担心你不能,因为所有你会得到的是指针的大小 .

    您需要传递数组的大小 . 将您的签名更改为:

    void get_details(int **a, int ROW, int COL)
    

相关问题