(code illustration)Re: [Courses] Re: pointers, array's, and sizeof()

Xp0nential Xp0nential Xp0nential at root-core.com
Sun Feb 3 10:57:24 EST 2002


here is a code illustration for people who better understand with examples (like me!!)

the numbers at the start of each line are just line numbers so I can reference them later..


1: #include <stdio.h>

2: void foo(char []);
3: int main()
4: {
5: char a[]="example";
6: printf("size of a %d\n",sizeof(a));
7: foo(a);
8: return 0;
9: }

10: void foo(char a[])
11: {
12: printf("3rd character %c\n",a[3]);
13: printf("size of a %d\n",sizeof(a));
14: }
the output of this program:

larry:/u10/rtannous/public_html $ gcc code.c
larry:/u10/rtannous/public_html $ ./a.out
size of a 8
3rd character m
size of a 4
larry:/u10/rtannous/public_html $

ok in this example ... 
on line 5 the compiler does not treat char a[] as a pointer. it is an array . it doesn't decay.
the proof when you use on line 6 sizeof you actually get  8 which is the size of the array

line 10 .. char a[] is passed as a formal function parameter thus the compiler treats it as if it was char *a; and we say it decays to a pointer to its first element.
on line 13 ... sizeof returns 4 bytes because thats the size of a pointer 4 bytes. and the reason for this result is that the compiler decayed a into a pointer at line 10.... thus sizeof returned the size of a pointer...
while on line 5 because the array was not part of a function formal parameter , sizeof returned the size of the array.. it wasn't decayed into a pointer..

hope this explains better, it does for me

regards
Xp0nential

_____________________________________________________________
[Root-Core Network] - [www.root-core.org] - Free E-mail



More information about the Courses mailing list