Answer DA1

#include <stdio.h>
#include <stdlib.h>

/* Puzzle D01 -- print each element in an array of ints, one per line */

void printArray( int size, int arr[] )
{
  int j;
  printf("index\tvalue\n");
  printf("-----\t-----\n");
  for ( j=0; j < size; j++ )
    printf(" %3d: \t%5d\n", j, arr[j] );
}


int main(int argc, char *argv[])
{
  int x[] = {0, 9, 23, -6, 5, 2, 71, 45, -9, 3 };
  
  printArray( 10, x );
    
  printf("\n");

  return 0;
}

Comments: When an array is a parameter to a function, its length must also be a parameter (unless all arrays in the program are always the same size). The length of an array cannot be determined from the array itself.

Details: In the call printArray( 10, x ) the parameter x actually stands for the address of the first byte of the array. The phrase "passing an array as a parameter" is not accurate (although commonly used). A more accurate phrase would be "passing an array address as a parameter".



Back to Puzzle Home