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

前端 未结 4 850
轻奢々
轻奢々 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 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!

提交回复
热议问题