Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

I am currently trying to get the length of a dynamically generated array. It is an array of structs:

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

I intialize my array like that:

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

And then resized it using realloc and started to fill it with data.

I then attempted to get its size using the code described here.

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

This operation returns 0 even though my array contains two elements.

Could someone please tell me what I'm doing wrong?

like image 469
beta Avatar asked Jan 03 '12 19:01

beta


3 Answers

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

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

mydata arr[2];

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

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

OTOH, length for dynamically allocated memory (using malloc()) should be maintained by the programmer (in the variables) - sizeof() won't be able to track it!

like image 114
Sangeeth Saravanaraj Avatar answered Oct 01 '22 10:10

Sangeeth Saravanaraj


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

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

like image 15
NPE Avatar answered Nov 09 '22 07:11

NPE


sizeof cannot be used to find the amount of memory that you allocated dynamically using malloc. You should store this number separately, along with the pointer to the allocated chunk of memory. Moreover, you must update this number every time you use realloc or free.

like image 5
Sergey Kalinichenko Avatar answered Nov 09 '22 08:11

Sergey Kalinichenko