The question is how to get the length of dynamically allocated 2D Arrays in C? I thought the code below should get the number of rows, but it doesn't.
char** lines;
/* memory allocation and data manipulation */
int length; //the number of rows
length = sizeof(lines)/sizeof(char*);
Any thoughts on this?
There is no (standard) way to calculate the length of a dynamic array in C. If you really, really, really, really must do it, there are non-portable solutions. Microsoft's compilers gives you the option of _msize. Then you could use the OS's allocation APIs to allocate and find the size of it.
Learn how to get the length of a 2D array in Java We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.
In your test case above sizeof
is returning the size of the type of lines
, and thus your length calculation is equivalent to sizeof(char**)/sizeof(char*)
and is likely to have the trivial result of 1
, always.
The underlying implementation of malloc
or new
must inevitably keep track of the size of the memory allocated for your variable. Unfortunately, there is no standard way to get the size of allocated block. The reason is due to the fact that not all memory block are dynamically allocated, so having the function that only works for only dynamic allocation is not so useful.
void fillwithzero(int* array) {
unsigned int size = getsize(array); // return 0 for statically allocated array ??
for(int i = 0; i < size; i++) {
array[i] = 0;
}
}
Let us say we have getsize
function that is capable of magically get the size of the dynamically allocated array. However, if you send pointer of a static array, or some array allocated by other means (e.g. external function) to fillwithzero
, this function will not be working. That is why most C function that accept array required caller to send the size or the maximum size of the array along with the array itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With