How to get the length of dynamically allocated two

2019-03-30 00:41发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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.

struct Line {
    char** text;
    uint32_t size;
};


回答4:

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:

int length = ...;
lines = malloc(length*sizeof(char*));

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.



回答5:

You pass it along with your value. There's no way to find that out.



回答6:

You can get the length of dynamically allocated memory, IF you use the NONPORTABLE MSVC/MinGW extension:

#include <malloc.h>
char *m = malloc(1234);
#ifdef __int64
printf("m size = %lu bytes", _msize(m) );
#endif