Afficher un message
Vieux 21/10/2007, 19h12   #5
Malcolm McLean
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sizeof and passing pointer


"jason" <jisis@notmal.com> wrote in message news:471b8fa0$0$14414
> But just to make sure; what does `decay' exactly mean in this case ? And
> what properties of the pointer, when passed to a function actually
> change ?
>


int main(void)
{
int array[10] = {1,2,3,4,5,6,7,8,910};

printf("array is %d bytes\n", (int) sizeof(array));
foo(array, 10);
}

void foo(int *ptr, int N)
{
int i;

printf("pointer is %d\n", (int) sizeof(ptr))'
/* treat as array */
for(i=0;i<N;i++)
print("%d\n", ptr[i]);
/* treat as pointer */
for(i=0;i<N;i++)
printf("%d\n", *ptr++);
}

in main your array is an array. When you pass it to foo it converts -
decays - into a pointer. arrays are very nearly, but not quite, constant
pointers. You can use the brackets notation on either an array or a pointer.
However you can also increment a pointer. Whilst sizeof(ptr) gives the size
of the memory item needed to hold the address, usually 4 bytes, whilst
sizeof(array) gives the size of the data in the array, probably either 20 or
40 bytes.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

  Réponse avec citation
 
Page generated in 0,05271 seconds with 9 queries