beta
beta

Reputation: 2633

How to get the length of a dynamically created array of structs in 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?

Upvotes: 9

Views: 13505

Answers (4)

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16597

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!

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 224864

You're trying to use a pretty well known trick to find the number of elements in an array. Unfortunately arr in your example is not an array, it's a pointer. So what you're getting in your sizeof division is:

sizeof(pointer) / sizeof(structure)

Which is probably always going to be 0.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 5

NPE
NPE

Reputation: 500257

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.

Upvotes: 15

Related Questions