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?
You can get the length of dynamically allocated memory, IF you use the NONPORTABLE MSVC/MinGW extension:
You pass it along with your value. There's no way to find that out.
The underlying implementation of
malloc
ornew
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.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) tofillwithzero
, 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.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 oflines
, and thus your length calculation is equivalent tosizeof(char**)/sizeof(char*)
and is likely to have the trivial result of1
, always.You cannot find the size of an array dynamically allocated. If you need pass this array to a function, create a structure containing the array and its size.
You cannot get the length of a dynamically allocated array in C.
When you allocate it, you need to store that length somewhere, so you know how long it is.
For instance:
If you need to pass this around to other functions, you will need to either pass them as separate parameters, or define a struct type that includes the length and the
lines
pointer.