Getting the size of a malloc only with the returned pointer

后端 未结 5 409
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 11:42

I want to be able to vary the size of my array so I create one this way:

int* array;
array = malloc(sizeof(int)*10);//10 integer elements

I

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 12:21

    The pointer is a pointer, and not an array. It can never be "recognized as an array", because it is not an array.

    It is entirely up to you to remember the size of the array.

    For example:

    struct i_must_remember_the_size
    {
        size_t len;
        int * arr;
    };
    
    struct i_must_remember_the_size a = { 10, NULL };
    a.arr = malloc(a.len * sizeof *a.arr);
    

提交回复
热议问题