UMBC CMSC 201
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help

An Example

The Program

/********************************************* ** File: pointers.c ** Author: R. Chang ** Modified by: S. Evans ** Date: 3/2/04 ** Modified to conform to current 201 standards ** Section: 101 ** EMail: bogar@cs.umbc.edu ** ** A simple program that shows the addresses of ** variables and that those addresses are stored ** in the pointer variables that point to them. **********************************************/ #include <stdio.h> int main () { int a = 1, b = 2; /* pointer declarations */ int *ptr1, *ptr2 ; /* show value and address of a and value of the pointer */ ptr1 = &a ; printf("a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n", a, &a, ptr1, *ptr1) ; /* show value and address of b and value of the pointer */ ptr1 = &b ; printf("b = %d, &b = %p, ptr1 = %p, *ptr1 = %d\n", b, &b, ptr1, *ptr1) ; /* change the value of b by dereferencing the ptr1 */ *ptr1 = 35 ; printf("b = %d, &b = %p, ptr1 = %p, *ptr1 = %d\n", b, &b, ptr1, *ptr1) ; /* let ptr2 also point to b */ ptr2 = ptr1 ; /* and also change b by dereferencing ptr2 */ *ptr2 = 17 ; printf("b = %d, &b = %p, ptr1 = %p, *ptr1 = %d\n", b, &b, ptr1, *ptr1) ; return 0; }

Output

linux1[75] % gcc -Wall -ansi pointers.c linux1[76] % a.out a = 1, &a = 0x7ffffa94, ptr1 = 0x7ffffa94, *ptr1 = 1 b = 2, &b = 0x7ffffa90, ptr1 = 0x7ffffa90, *ptr1 = 2 b = 35, &b = 0x7ffffa90, ptr1 = 0x7ffffa90, *ptr1 = 35 b = 17, &b = 0x7ffffa90, ptr1 = 0x7ffffa90, *ptr1 = 17 linux1[77] %


CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:14:16 EDT