9

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?

Community
  • 1
  • 1
beta
  • 2,583
  • 15
  • 34
  • 46
  • You can't programmatically obtain the size of a dynamically allocated array other than by manually saving the size in a variable, using a sentinel value, etc – Seth Carnegie Jan 03 '12 at 19:06

4 Answers4

15

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3
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!

Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
2

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469