Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of dynamically allocated two dimensional arrays in C

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?

like image 299
aminfar Avatar asked Sep 12 '10 03:09

aminfar


People also ask

How can we find out the length of an array dynamically in C?

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.

How do I find the LEN of a 2D array?

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.


2 Answers

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.

like image 142
Mark Elliot Avatar answered Oct 01 '22 00:10

Mark Elliot


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.

like image 29
tia Avatar answered Oct 01 '22 01:10

tia