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
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.
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!
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
.
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.