/* pointers.c - Brief review on pointers Copyright 2009: Francisco Jose Monaco This program is Free Software and can distributed under the GNU GPL v3 as found in http://www.gnu.org/licenses/gpl.txt. */ #includeint main (void) { int i, m, n; /* Supose we have these variables. */ char a[10]; /* A static array of 10 chars.*/ int b[10]; /* An static array of 10 ints. */ char *p; /* A pointer to an char .*/ int *q; /* A pointer to a int. */ /* Let's fill in a[] and b[] with arbitrary values.*/ for (i=0; i<10; i++) { b[i] = 30*i; a[i] = b[i]; } /* Run the program and try to understand the generated output.*/ /* The symbol 'a' is a constant poiting to an static array array of 10 char. We can get the value in 'a': is the address where the array is located in the memory, i.e. the memory position of the first byte of the array.*/ printf ("a=%p\n", a); /* To get the value stored in the first position of 'a' we can write '*a'. */ printf ("*a=%d\n", *a); /* To get the value stored in the 2nd positions of 'a' we can write *(a+1), i.e. the value stored in the address "a plus 1" (second byte of the array).*/ printf ("*(a+1)=%d, *(a+2)=%d\n", *(a+1), *(a+2)); /* This is equivalent to writing a[0], a[1], a[2]. It's just an anternative syntax.*/ printf ("*(a+0)=%d, *(a+1)=%d, *(a+2)=%d\n", *(a+0), *(a+1), *(a+2)); printf (" a[0]=%d, a[1]=%d, a[2]=%d\n", a[0], a[1], a[2]); /* The variable p nows contain the value of 'a', i.e. the adress of the array a[] in memory. */ p = a; /* To get the both value of p and the value pointed by 'p' we write: */ printf ("p=%p, *p=%d\n", p, *p); /* Both 'a' and 'p' now hold the same value: the address of the array a[]. The difference between 'a' and 'b' is that 'a' is a constant and 'p' is a variable; we can change the value of p, but not the value of 'a'. */ printf ("*(p+2)=%d, *(a+2)=%d\n", *(p+2), *(a+2)); /* Now consider the array b[]. Why is it for times longer than a[] in bytes? */ printf ("a is %d bytes long, b is %d bytes long\n", sizeof(a), sizeof(b)); /* So, why does this happen? */ for (i=0; i<10; i++) printf ("(%d, %d) ", a[i], b[i]); printf ("\n"); /* And this? Tip: remember that it's pointer arithmetic.*/ printf ("%d\n", (int) (a+1) - (int) a); printf ("%d\n", (int) (b+1) - (int) b); /* If you understand the above code, then you can also understand this: */ q = (int *) p; printf ("*(q+0)=%d\n", *(q+0)); /* And finally, this: */ m = 1024; n = * (char *) (&m+1); printf ("n=%d\n", n); return 0; }
Última atualização: quinta, 8 outubro 2009, 20:30