如何获得由双指针指向二维数组的大小? [英] How to get size of 2D array pointed by a double pointer?

查看:591
本文介绍了如何获得由双指针指向二维数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从双指针获得行和一个二维数组的列数指向数组。

I am trying to get the number of rows and columns of a 2D Array from a double pointer pointed to the array.

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

以上功能需要打印的大小,我要去错在何处的详细信息。

Above function needs to print the details of the size, where am going wrong.

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创建阵列。

I am using malloc to create the array.

如果我用这样的事情是什么

What if I use something like this

柱= sizeof的(A)/ sizeof的(INT)?

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

推荐答案

C不办反映。

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

Pointers don't store any metadata to indicate the size of the area they point to; if all you have is the pointer, then there's no (portable) way to retrieve the number of rows or columns in the array.

您要么需要传递的信息与指针一起,否则你将需要使用数组本身的警戒值(类似于C字符串如何使用0终结,虽然这只是给你的逻辑的字符串,它可以是小于的尺寸的物理的所占用的阵列)的大小。

You will either need to pass that information along with the pointer, or you will need to use a sentinel value in the array itself (similar to how C strings use a 0 terminator, although that only gives you the logical size of the string, which may be smaller than the physical size of the array it occupies).

C语言程序的发展,丹尼斯里奇解释他希望聚合类型,如数组和结构不只是重新present抽象类型,但要重新present,将占用内存或磁盘空间位的集合;因此,该类型内没有元数据。这就是你希望跟踪自己的信息。

In The Development of the C Programming Language, Dennis Ritchie explains that he wanted aggregate types like arrays and structs to not just represent abstract types, but to represent the collection of bits that would occupy memory or disk space; hence, no metadata within the type. That's information you're expected to track yourself.

这篇关于如何获得由双指针指向二维数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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