How to get size of 2D array pointed by a double pointer?
Asked Answered
H

2

8

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

I am using malloc to create the array.


What if I use something like this

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

Helvetia answered 18/10, 2012 at 23:39 Comment(0)
D
11

C doesn't do reflection.

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.

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).

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.

Duet answered 19/10, 2012 at 0:22 Comment(0)
M
4
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);
}

I'm afraid you can't, as all you will get is the size of the pointer.

You need to pass the size of the array. Change your signature to:

void get_details(int **a, int ROW, int COL)
Mustachio answered 18/10, 2012 at 23:44 Comment(2)
Other languages that allow you to get array sizes, like Fortran or Python (numpy), only allow it because they carry around extra data in the array to track the size. C doesn't do this, you have to track it yourself.Taro
@Helvetia It's not possible, at least not portably. It may be possible with some implementations, but not in general. My glibc offers size_t malloc_usable_size(void*) in malloc.h, but that gives you the usable size, and not how much you asked for, so it can be more (and most of the time is, here).Marlowe

© 2022 - 2024 — McMap. All rights reserved.