Pointer Basics: CSE 130: Introduction To Programming in C Spring 2005
Pointer Basics: CSE 130: Introduction To Programming in C Spring 2005
Pointers
Pointer Addressing
Pointer Dereferencing
Ex:
in the pointer!
int i, *p;
p = &i;
Pointer Examples
More Examples
int a = 7;
double x, y, *p;
p = &x;
*p = 3; /* a is now 3 */
printf(a = %d\n, a); /* prints 3 */
Printing Pointers
Pointers to void
p = v; /* legal */
v = p; /* legal */
v = 1; /* illegal */
7
Call-by-Reference
An Example
void swap (int *p, int *q)
int tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
9
Pointer Arithmetic
If pa is a pointer to an array A:
A[i] can be written as *(pa + i)
Where pointers are concerned, (pa + 1)
10
12
An Example
int A[] = {1, 3, 5, 7, 9};
int *pa = A; /* pa points to A[0] */
printf(%d, *pa); /* prints 1 */
printf(%d, *(pa + 3)); /* prints 7 */
pa++; /* pa now points to A[1] */
printf(%d, *pa); /* prints 3 */
Equivalent to:
(*pointer_to_structure).member_name
Structure Pointers
struct student temp, *p = &temp;
temp.grade = A;
p -> lastName = Bushker;
p -> studentID = 590017;
printf(%c\n, (*p).grade);
15
14