COMP1410 Lab 4-Pointers Solved

35.00 $

Category:

Description

5/5 - (1 vote)

Learn to use pointers.

  1. Consider the following C program. Assume that memory addresses are expressed in decimal numbers and an integer takes 4 bytes. Also, assume ids = &ids[0] = 2000. What would be printed by the following program? Do NOT compile and execute this program as it will not provide the correct results – do the tracing of the program by hand and using only the assumptions stated.

#include <stdio.h> int main(){ int ids[3] = {100,200,300}; int *salary, salary1, salary2, *salary3; salary1 = ids[0] * ids[1]; salary = &ids[1] ;       salary2 = *(ids+1)* *(ids+2); salary3 = ids+2; printf(“*salary = %d\nsalary1 = %d\n”, *salary, salary1); printf(“salary2 = %d\nsalary3 = %p\n”, salary2, salary3);

}

  1. Write a documented function called Largest that finds and returns the address of the largest element in the array passed to it. (Assume an integer array of size 10). You must use pointer arithmetic on the array name instead of the array subscript notation to implement the function. (NOTE: This function will be included as part of step 4 below.)

int *Largest( int *array, int size );

  1. Write a documented function called Swap that takes two integer pointers and exchanges the values of each. It returns void. Example: given two integers ‘a = 2’ and ‘b = 4’, after Swap (&a, &b) is called, ‘a’ will be 4 and ‘b’ will be 2. (NOTE: This function will be included as part of step 4 below.)

void Swap( int *x, int *y );

  1. Write a complete, well documented C language program (called c) to test both the functions Largest and Swap. In order to test your functions you will need to define and populate an array, within main, that you can pass to Largest, and also

two initialized int variables to pass into  Swap; do not forget to write printf() statements to show Before/After views of any data that will undergo changes.  Ensure that your testing clearly demonstrate each function and its required result.  There is no need for a menu, nor for the program logic to repeat itself (unless you choose to implement such logic).

  • lab04-mp201u.zip