How to get the length of a dynamically created array of structures in C?

I'm currently trying to get the length of a dynamically generated array. This is an array of structures:

typedef struct _my_data_ { unsigned int id; double latitude; double longitude; unsigned int content_len; char* name_dyn; char* descr_dyn; } mydata; 

I initialize my array as follows:

 mydata* arr = (mydata*) malloc(sizeof(mydata)); 

And then resized it with realloc and started populating it with data.

Then I tried to get its size using the code here .

 sizeof(arr) / sizeof(arr[0]) 

This operation returns 0 , although my array contains two elements.

Can someone please tell me what I am doing wrong?

+8
c
source share
4 answers

If you need to know the size of a dynamically allocated array, you must track it yourself.

The sizeof(arr) / sizeof(arr[0]) method works only for arrays whose size is known at compile time, and for C99 arrays of variable length .

+14
source share

sizeof cannot be used to find the amount of memory that you allocated dynamically using malloc . You must save this number separately with a pointer to the allocated part of memory. In addition, you must update this number every time you use realloc or free .

+5
source share
 mydata* arr = (mydata*) malloc(sizeof(mydata)); 

is a pointer , not a array . To create an array of two mydata elements, you need to do the following

 mydata arr[2]; 

Secondly, to select two mydata elements using malloc() , you need to do the following:

 mydata* arr = (mydata*) malloc(sizeof(mydata) * 2); 

OTOH, the length for dynamically allocated memory (using malloc() ) must be supported by the programmer (in variables) - sizeof() will not be able to track it!

+2
source share

You are trying to use a fairly well-known trick to find the number of elements in an array. Unfortunately, arr in your example is not an array, it is a pointer. So what do you get in your sizeof unit:

 sizeof(pointer) / sizeof(structure) 

Most likely it will be 0.

+1
source share

All Articles