Pointers 101 • pointer: memory address of a piece of data • Why pointers? • • Address can be used to access/modify the data from any function Pass a pointer to the data instead of a whole copy of the data Pointers required for file I/O Used in many data structures, e. g. , linked lists • Two operators which are opposites • address-of operator &: memory address of data • indirection (contents at) operator *: data stored at an address • also used to declare a pointer variable
Pointers • Store memory addresses in pointer variables int i = 3; int *i. Ptr = &i; // address of i // *i. Ptr: value that i. Ptr points to i. Ptr 0 x 7 fff • Can use pointer to change contents at memory location • *i. Ptr = 5; // same result as i = 5; • printf("Value of i: %dn", i); • Output: Value at i: 5 • Note the uses of *i. Ptr above: • Declaration: int *i. Ptr: i. Ptr points at an int • Dereferencing (accessing contents at): *i. Ptr = 5; i 3 Addr: 0 x 7 fff
More on Pointers int number = 23; *p 1, *p 2; p 1 = &number; p 2 = &number; printf ("*p 1 = %d What’s the Output ? number 23 p 1 p 2 *p 2 = %d ", (*p 1), (*p 2));
Pointer Arithmetic int arr[] = {3, 1, 8, 7}; int *p = arr; // p points to arr[0] • p + i points to arr[i] • arr + i points to arr[i] • Address value increases by i * sizeof(int) • *(arr + 1) is 1 • *(arr + 2) is 8
Pointer Arithmetic • Only addition, subtraction and comparison operations are allowed for pointer variables • Array name is pointer to first element of array • Pointer arithmetic is done relative to the base type int *p =NULL, *q =NULL; int x[4] = {25, 37, 77, 99}; p = &x[0]; // OR just p = x; q = p; q++; // advances by sizeof(int) bytes, *q is 37 printf (“value is %d”, *(q + 2)); // value is 99 • A pointer can be used to iterate through an array/string char str[] = "Test"; char *p; int i; for( p = str, i=0; *p != '