Originally Posted by
ozumsafa
But I did array=malloc(10*sizeof(char)) before I printed the sizeof(*array) .. Dint I allocate a 10 char memory to array ? So shouldnt it print out 10??
Code:
#include <stdio.h>
#include <stdlib.h>
unsigned long foo( int (*p_stack)[5] )
{
return sizeof p_stack;
}
int main( void )
{
int p_auto[] = { 0, 1, 2, 3, 4, };
int *p_heap = malloc( sizeof *p_heap * 5 );
if ( p_heap )
{
printf( "sizeof p_auto = %lu\n", sizeof p_auto );
printf( "sizeof p_auto[0] = %lu\n", sizeof p_auto[0] );
printf( "sizeof p_auto / sizeof p_auto[0] = %lu ;)\n", sizeof p_auto / sizeof p_auto[0] );
printf( "sizeof p_heap = %lu\n", sizeof p_heap );
printf( "sizeof *p_heap = %lu\n", sizeof *p_heap );
printf( "sizeof p_stack = %lu\n", foo( &p_auto ) );
free( p_heap );
p_heap = NULL;
}
return 0;
}
/**
* sizeof p_auto = 20
* sizeof p_auto[0] = 4
* sizeof p_auto / sizeof p_auto[0] = 5 ;)
* sizeof p_heap = 4
* sizeof *p_heap = 4
* sizeof p_stack = 4
*/
Building on what the others had said, the size of some object really depends how it was allocated, and where in the code you decide to ask. sizeof is a special function provided by the compiler that computes the size of an object on a function's stack.
And you will notice that pointers often occupy the stack in a function; ones like p_heap might be 4 or longer on other systems. The size of a pointer is the byte-width RAM requires to store a memory address. The size of an array on the other hand is much different. The array uses all the memory it needs from the function stack. Therefore we can conclude that the size of p_auto is accurate.
So, what to learn from all of this: keep a variable handy that knows the length of a pointed to array, because it is hard to tell otherwise. If you need to know the size of a pointed to object (like int), dereference the pointer first.