Holla Tech - Learn

Functions with Array Parameters
 

An array cannot be passed by value to a function. However, an array name is a pointer, so just passing an array name to a function is passing a pointer to the array.

Consider the following program: 

int add_up (int *a, int num_elements);

int main() {
  int orders[5] = {100, 220, 37, 16, 98};

  printf(“Total orders is %d\n”, add_up(orders, 5));

  return 0;
}

int add_up (int *a, int num_elements) {
  int total = 0;
  int k;

  for (k = 0; k < num_elements; k++) {
    total += a[k];
  }

  return (total);

 

Program output is: “Total orders is 471”


Functions that Return an Array
 

Just as a pointer to an array can be passed into a function, a pointer to an array can be returned, as in the following program:

Note that a pointer, not an array, is declared to store the value returned by the function. Also note that when a local variable is being passed out of a function, you need to declare it as static in the function.

NOTE!
Keep in mind that a[k] is the same as *(a + k).

BACK NEXT 

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT