Passing pointers as argument in C functions

Viewed 63

I read all the answered questions on this topic I could find, but none answer my question...

I am still reading about pointers in C and now I am trying to understand how pointers can be passed through a function. However, there is something I dont understand in the following code (taken from tutorialspoint.com):

#include <stdio.h>

/* function declaration */
double getAverage(int *arr, int size);

int main () {

   /* an int array with 5 elements */
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   /* pass pointer to the array as an argument */
   avg = getAverage( balance, 5 ) ;

   /* output the returned value  */
   printf("Average value is: %f\n", avg );
   return 0;
}

double getAverage(int *arr, int size) {

   int  i, sum = 0;       
   double avg;          

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }

   avg = (double)sum / size;
   return avg;
}

When getAverage(balance, 5) is called, I am passing in a pointer to the first element of the balance array (as I learned in my last question). But how are we accessing the actual content of the array (sum += arr[i]) in the for loop inside getAverage?

I read the following source: http://c-faq.com/aryptr/aryptrequiv.html, I am pretty sure the sentence after the second footnote is explaining this. But I still dont understand it.

Any help is appreciated!

2 Answers

In getAverage, arr points to the first element of balance, as you noted. So *arr can be used to access that first element (either reading it or writing it), just as balance[0] would do in the caller.

To access the second element, you can add one to the pointer before dereferencing it, i.e. *(arr + 1), and so on. This is in fact equivalent to arr[1]. In particular, arr[i] is equivalent to *(arr + i). It adds the offset i to the address arr, scaling by the size of what's being pointed to, then dereferences the pointer.

Because arrays are allocated as a contiguous block of memory, you only need to know two things to access any element in an array:

  1. The start position of this block of memory (i.e. arr).
  2. The position of an element relative to the start position (i.e. the index i).

So calling arr[i] will effectively count i spaces from the array's start position, returning the value at that index.

Related