UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

5.12.  Activities

5.12.1.  Arrays as special case of pointers

Work Plan

Suppose that you have the following array declaration:

int table[] = {10, 20, 30, 40, 50};

If you printed table[0], you would see 10. But what if you were to print *table? Would it print anything? If so, what? If you thought an error message would print because table is not a pointer but an array, you would be wrong; an array name is a pointer. If you print *table, you also would see 10.

You can make a pointer that refers to the first element of an array by simply assigning the array name to the pointer variable. If an array is referenced by a pointer, the elements in the array can be accessed with the help of the pointer:

#define SIZE 10
char *ptr_char;
char chars[SIZE];
ptr_char = chars;

The name of the array, by itself, is a shorthand way of saying ptr_char = &chars[0]; they mean the same thing.

You can increment or decrement a pointer. If you increment a pointer, the address inside the pointer variable increments. The pointer does not always increment by 1, however. It increments as the size of the data type it refers to. This way, chars[2] and *(ptr_char + 2) are equivalent.

Having this in mind, you will calculate the average between every pair of integers of two arrays. You will have to print the integers of the arrays and calculate and print that average. Create a file with name arrays_as_pointers.c in your development environment and implement the following functionality (you may notice that it is the same program as the one of basic arrays; however, now you have to pass the array as a pointer):

  1. A function that prints out the integer values of an array: void print_array(int *array);

  2. A second function that calculates the average between the two elements in a same position of two arrays and prints that average value: void calculate_average(int *array1, int *array2);. For the first position in every array, sum the two integers and divide the result by two, prints the result out and makes the same for the rest of positions in the arrays.

  3. A main function that declares and initializes the two arrays with 10 integers (whatever you want), such as int array1[] = {1,5,7,3,12,...};, and that makes use of the first and second function to both print the values of the arrays and print out the averages.