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

≡放荡痞女 提交于 2019-11-30 15:16:55

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!