Passing Single-Dimension Arrays to Functions


In C, you cannot pass an entire array as an argument for any activity. You can, however, move the pointer to an array by specifying the name of the array without formatting.

int numbers[10];

Using the numbers array, you can create a pointer to the first element. Thus, the segment of the following program assigns the address a to the first element of the number:

int numbers[10];
int *a;
a = numbers;

You can also specify the address of the first element of an array using the & operator. For example, numbers and &numbers[0] both produce the same results. However, in professionally written C code, you will rarely see &numbers[0].

Sized array as a parameter

Program
#include <stdio.h>
void func(int x[10]);
int main() {
  int a[10];
  
  for(int i=0;i<10;i++)
   {
    a[i] = i;
   }
  func(a);
  return 0;
}
void func(int x[10]) /* sized array */
{
 for(int i=0;i<10;i++)
  {
   printf("%d ",x[i]);
  }
}

Unsized array as a parameter

Program
#include <stdio.h>
void func(int x[]);
int main() {
  int a[10];
  
  for(int i=0;i<10;i++)
   {
    a[i] = i;
   }
  func(a);
  return 0;
}
void func(int x[]) /* unsized array */
{
 for(int i=0;i<10;i++)
  {
   printf("%d ",x[i]);
  }
}

Pointer as a parameter

Program
#include <stdio.h>
void func(int *p);
int main() {
  int a[10];
  
  for(int i=0;i<10;i++)
   {
    a[i] = i;
    func(&a[i]);
   }
  return 0;
}
void func(int *p) /* pointer */
{
 int value = *p;
 printf("%d ",value);
}

All three declaration methods give the same result because each tells the compiler that an integer pointer is being found. The first assigns a standard array declaration. The second is that a modified version of an array declaration only specifies that certain length types must be accepted. The third declaration actually uses pointers. You can see that the length of the array is not as important as the function because C does not check any boundaries.