Getting the size of a malloc only with the returned pointer

arrays, c, malloc, pointers, sizeof

Solution

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);

Problem

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 can use this like an array as you normally would, however when I try to find the size of it like so: ``` size = sizeof(array)/sizeof(int); ``` I get the answer 1 because its not recognizing it as pointing to an array How can I get the size of the array ? (I know its not technically an array but is there a way to work out the whole size of the allocated memory block ?) Also am I right in assuming what I have stated in the description ? If I am technically wrong about something please correct me.

Original source