5.19 Pointers - 1 |
&
Address operator Kernighan p 94 Deitel p30.
This operator returns the address of the object.
*
Indirection Operator (dereference) Kernighan p 94.
An example program that:
/* Program to look at pointers */ /* L Taber Feb 17, 2001 PCC */ #include <stdio.h> #include <stdlib.h> /* returns three results */ int sumANDswap(int *a, int *b); int printab(int x, int y, char *string); int a = 1; /* external variable */ /* initilized only once */ int *ptr; int main() { int b; /* auto variable */ int sum; /* for return value */ ptr = malloc( sizeof a ); *ptr = 42; b=5+a; printab(a, b, "a & b "); sum = sumANDswap(&a, &b); printab(a, b, "a & b "); printf("sum= %d\n\n", sum); printab(b, *ptr, "b & *ptr "); sum = sumANDswap(&b, ptr); printab(b, *ptr, "b & *ptr "); printf("sum= %d\n", sum); } /* returns three results */ int sumANDswap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; return( *a + *b ); } /* strings are really character pointers ! */ int printab(int x, int y, char *string) { return printf(" %s %d %d\n", string, x, y); }
This program is available by anonymous ftp at:
ftp://lt.tucson.az.us/pub/c/prt1.c.
The anotated output on my system looked like this:
a & b 1 6 a & b 6 1 sum= 7 b & *ptr 1 42 b & *ptr 42 1 sum= 43
I am using gcc version 2.95.2 20000220 (Debian GNU/Linux).
main()
does not change.
a
does not change.
b
is placed on the stack
at a lower address.
int
on the malloc
-ed.
The heap is grows toward the stack.
5.19 Pointers - 1 |