tags:

views:

99

answers:

4

See this example!



int main( int argc, char ** argv )
{
    int *ptr = malloc(100 * sizeof (int));

    printf("sizeof(array) is %d bytes\n", sizeof(ptr));
}

The printf function return only 4 bytes! What is wrong?

Thanks so much!!!

+8  A: 

Nothing is wrong. You are asking for, and getting, the size of the pointer on your platform.

It is not in general possible to get the size of the memory block that a pointer points at, you must remember it yourself if you need it later.

unwind
+1  A: 

You cannot print the size of the memory block you received. Either malloc allocates all the memory you requested or it does not (and returns NULL).

The sizeof() operator does what you request: it tells you the size of the pointer - and the pointer itself occupies 4 bytes in memory.

PP
+1  A: 

Nothing is wrong, that's the size of any pointer on a 32 bit platform.

sisis
+2  A: 

On some platforms there is the "msize" function that returns the size of an area allocated by malloc/calloc/strdup. But this is not standard.

Giuseppe Guerrini