UMBC CMSC 201 Fall '05
CSEE | 201 | 201 F'05 | lectures | news | help

Pointer Example

The standard C routine scanf is where most people first see pointers. In the example below, the data read from standard input is placed in the variable i int i; scanf("%d", &i);

Recall that C uses call by value for scalars, which means that (a copy of) the address of i is passed to scanf. The scanf routine reads in the data, and places it in the indicated address.

In general, if a subroutine needs to modify a scalar variable, it needs to receive the address of that variable as a parameter. For example,

#include <stdio.h> void Add2 (int *iPtr); int main() { int k = 4; Add2 (&k); printf("%d\n", k); /* prints 6 */ return 0; } void Add2(int *iPtr) { *iPtr += 2; }


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

Sunday, 25-Sep-2005 12:06:04 EDT