【问题标题】:How to get size of 2D array pointed by a double pointer?如何获取双指针指向的二维数组的大小?
【发布时间】:2012-10-09 13:02:19
【问题描述】:

我试图从指向数组的双指针中获取二维数组的行数和列数。

#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) ?

【问题讨论】:

    标签: c multidimensional-array double-pointer pointer-to-array


    【解决方案1】:

    C 不做反射。

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

    您需要将该信息与指针一起传递,或者您需要在数组本身中使用一个标记值(类似于 C 字符串如何使用 0 终止符,尽管这只会为您提供 逻辑 字符串的大小,可能小于它所占用的数组的物理 大小)。

    The Development of the C Programming Language 中,Dennis Ritchie 解释说,他希望像数组和结构这样的聚合类型不仅代表抽象类型,而且代表会占用内存或磁盘空间的位集合;因此,该类型中没有元数据。这是您应该跟踪自己的信息。

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

      • 其他允许您获取数组大小的语言,如 Fortran 或 Python (numpy),只允许它,因为它们在数组中携带额外的数据来跟踪大小。 C 不这样做,你必须自己跟踪它。
      • @Yash 这是不可能的,至少不能移植。在某些实现中可能是可能的,但不是一般情况下。我的 glibc 在malloc.h 中提供了size_t malloc_usable_size(void*),但这给了你可用的大小,而不是你要求的多少,所以它可以更多(而且大部分时间都在这里)。
      猜你喜欢
      • 2018-02-15
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 2012-01-26
      相关资源
      最近更新 更多