Getting the size of a malloc only with the returned pointer

后端 未结 5 413
被撕碎了的回忆
被撕碎了的回忆 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

    There's no standard way to do what you ask. Some compilers may provide a function for that, or some other allocators may have such a function, but, as already said there's nothing standard.

    Notice that the sizeof applied over arrays does not work because it recognizes the pointer "as from an array": it just recognizes its argument as an array (sizeof is one of the few contexts in which an array do not decay to a pointer to its first element); once your array decays to a pointer sizeof will only yield the size of the pointer.

提交回复
热议问题