How to get the size of a 2D array pointed to by a double pointer?

I am trying to get the number of rows and columns of a two-dimensional array from a double pointer pointing to an 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 the function you need to print the size details where the wrong thing happens.

 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 use malloc to create an array.


What if I use something like this

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

+4
source share
2 answers

C is not reflected.

Pointers do not store metadata to indicate the size of the area they point to; if all you have is a pointer, then there is no (portable) way to get the number of rows or columns in an array.

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

In Developing the C Programming Language, Dennis Ritchie explains that he wanted aggregated types, such as arrays and structures, to not only represent abstract types, but to represent a collection of bits that would occupy memory or disk space; therefore, no metadata inside this type. This is the information you expect to track.

+6
source
 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 cannot, since all you 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) 
+3
source

Source: https://habr.com/ru/post/1440670/


All Articles