next up previous contents index
Next: Allocation Up: Pointers Previous: Pointers and subroutines   Contents   Index

Arrays

Given the considerations of the previous section, what would you think the following program to produce?
#include <stdio.h>
void testit(int[]);
int main(void) {
  int i[] = {1,2,3,4,5};
  printf("Before testit(), i[0]=%d\n", i[0]);
  testit(i);
  printf("After testit(), i[0]=%d\n", i[0]);
  return 0;
}
void testit(int in[]) {
  printf("Within testit(), upon entering, in[0]=%d\n", in[0]);
  in[0] = 11;
  printf("Within testit(), before leaving, in[0]=%d\n", in[0]);
}
You would not be faulted for guessing
Before testit(), i[0]=1
Within testit(), upon entering, i[0]=1
Within testit(), before leaving, i[0]=11
After testit(), i[0]=1
as was the case for passing in a single scalar value by value. However, what it actually produces is
Before testit(), i[0]=1
Within testit(), upon entering, i[0]=1
Within testit(), before leaving, i[0]=11
After testit(), i[0]=11
which is analagous to what happens when passing in a variable through a pointer. The reason for this is that arrays, at a fundamental level, are passed in through pointers; the preceding program is equivalent to
#include <stdio.h>
void testit(int *);
int main(void) {
  int i[] = {1,2,3,4,5};
  printf("Before testit(), i[0]=%d\n", i[0]);
  testit(&i[0]);
  printf("After testit(), i[0]=%d\n", i[0]);
  return 0;
}
void testit(int *in) {
  printf("Within testit(), upon entering, in[0]=%d\n", in[0]);
  in[0] = 11;
  printf("Within testit(), before leaving, in[0]=%d\n", in[0]);
}
Thus, essentially what is being passed in is the address of the zeroth member of the array.

Here's another example of a routine that just prints out the values of the array passed in:

#include <stdio.h>
void printit(int[]);
int main(void) {
  int i[] = {1,2,3,4,5};
  printit(i);
  return 0;
}
void printit(int in[]) {
  int i;
  for(i=0; i<5; i++) {
    printf("in[%d]=%d\n", i, in[i]);
  }
}
written more explicitly using pointers:
#include <stdio.h>
void printit(int *);
int main(void) {
  int i[] = {1,2,3,4,5};
  printit(&i[0]);
  return 0;
}
void printit(int *in) {
  int i;
  for(i=0; i<5; i++) {
    printf("in[%d]=%d\n", i, *in);
    in = in + 1;
  }
}
Note here the use of in = in + 1 to move the pointer to the next address location, enabling us to access the next array element.