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

前端 未结 4 844
轻奢々
轻奢々 2021-01-02 12:16

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          


        
相关标签:
4条回答
  • 2021-01-02 12:46

    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.

    0 讨论(0)
  • 2021-01-02 13:00
    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!

    0 讨论(0)
  • 2021-01-02 13:08

    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.

    0 讨论(0)
  • 2021-01-02 13:11

    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.

    0 讨论(0)
提交回复
热议问题