CSCE 206 Lab Structured Programming in C SPRING 2019 Lecture 7
Pointer Pointers are variables that stores/points the address of another variables Address refers to the memory location of a variable
Pointer operators & is the address operator. It refers to the address of a variable. * is the dereference operator. It refers to value at a specific address. Why pointer? Call by reference Dynamic Memory Allocation
Pointer example int main(void) { int var = 50; int *ptr; ptr=&var; printf("value is %d\n", var); printf("value is %d\n", *ptr); printf("Address of value is %d", ptr); return 0; } Prints: value is 50 Address of value is 1001
Pointers on consecutive memory If the data you are iterating is consecutive in memory, such as arrays, you can also access consecutively using pointer arithmetic If you have a pointer to any array position you can use: ptr++ to go to the next array position ptr-- to go to the previous array position ptr += x to skip x array positions (beware, it must be within the array) ptr -= x same as previous but in the other direction
Pointers on consecutive memory To iterate through consecutive memory you need an end condition, for example, the address of the last valid consecutive memory In arrays it would be &array[size-1] The first item to iterate could be any, typically you want to use &array[0] The pointer arithmetic calculates automatically the address depending on the size of the pointer type you are using (char, int, double, …) Char would typically increase 1B, int 4B, double 8B
Iterate array with pointers int array[10]; int *start = &array[0]; int *end = &array[9]; int *current = start; while (current <= end) { scanf("%d", current); current++; }
Practice Problem-1 Write a program that adds 2 integers using pointers. Take 2 integers in 2 variables named a and b. Add those numbers and save it in another variable. Print the address and values of a, b and c.
Practice Problem-2 Write a program that takes 3 integers as input and find the largest number among them. Use pointer variables to do the comparison and output printing.
Practice Problem-3 Write a program that takes 2 integers as input and swap their values. You are required to write a function named SwapValues, that takes 2 pointer variables and within the function swap the values. Print the output from main function.