|
// more pointers
#include <iostream.h>
int main ()
1 {
2 int numbers[5];
3 int * p;
4 p = numbers; *p = 10;
5 p++; *p = 20;
6 p = &numbers[2]; *p = 30;
7 p = numbers + 3; *p = 40;
8 p = numbers; *(p+4) = 50;
9 for (int n=0; n<5; n++)
10 cout << numbers[n] << ", ";
11 return 0;
Ok first off some general things.
In C the int consists of 16 bits or 2 bytes.
A pointer declared in line 3 is 32 bits or 4 bytes.
A variable declared an array (like in line 2) is actually a pointer to the first element of that array. Because of this it behaves like a pointer. In other words numbers is actually a pointer to the start of a 10 consecutive bytes in memory.
All this means that line 4 actually means that p is now pointing at the location numbers is pointing to. The star in line 4 (*p = 10) means you want to access the location the pointer p is pointing to not the actual pointer. Thus p being numbers and *p being 10 means that numbers[0] is 10.
numbers is (10, nd , nd , nd , nd) where nd is not defined.
Since pointers are basicly unsigned double ints you can increment. Since the p points to the first element of numbers by incrementing it in line 5 p points to the second element of numbers or numbers[1] (remember that arrays always start with 0 in c). Then *p = 20 means that the second element of numbers is 20.
numbers is (10, 20 , nd , nd , nd)
Line 6 is a bit tricky. The & means you want the location of a variable. And numbers[2] is a variable. The tricky part is that numbers is a pointer while numbers[2] is a int. So
&numbers[2]
is actually a pointer to the third element of numbers. This is then assigned 30 (*p=30)
Now numbers is (10, 20, 30, nd, nd)
Since pointers are numbers you can add 3 to the location of the first element of numbers in line 7 to get p to point to the 4th element of numbers. After line 7 numbers is
(10, 20, 30, 40, nd)
Line 8 is pretty much the same reasoning as in line 7 except you add 4 to p which was pointing to numbers[0] and place 50 in that location giving you
(10, 20, 30, 40, 50)
Lines 9, 10 print out the numbers array. No {} are needed for oneliners in c after a for.
Line 11 returns 0 the default for no errors in c.
To sum it up:
Array variables like "numbers" are pointers to the first element of an array.
numbers is a pointer variable while numbers[n] is an int variable
*p denotes the actual data at location p.
&numbers[n] is the address to the n element in an array. &n would give you the address at wich the variable n was stored.
Last edited by elmers; 02-18-2004 at 09:23 AM.
|