Passing 1-D Array to a Function in C

In the chapter One Dimensional Array and Function in C , we have discussed that when an array is passed to a function, the changes made by the function affect the original array. After studying about pointers we are in the position to understand why this happens. But before we study this, I want to make a few points clear.

In the above-mentioned chapter, we have also learned that when a 1-D array is passed to the function, it is optional to specify the size of the array in the formal arguments. So if we are passing an array of 5 integers then the formal argument of a function can be written in the following two ways.

1st way:

2nd way:

In the chapter Pointers and 1-D arrays, we have also learned that name of the array is a constant pointer to the 0th element of the array. In our case my_arr is a pointer to 0th element of the array, in other words, my_arr points to the address of element 11. So the base type of my_arr is a pointer to int or (int *). Hence the formal argument of a function can be also be declared as pointer to int or (int *):

3rd way:

Essentially in all the three cases base type of a is a pointer to int or (int *), we are just using three different ways to represent them.

Okay let’s get back to our original discussion: Why do the changes made to an array inside a function affect the original array? The following program answers this question.

Expected Output:

How it works:

We know that my_arr is a pointer to the first element of the array. So we can pass my_arr to the function my_func() without using & operator. In line 15, the my_func() is called with an actual argument of my_arr which is then assigned to a. Again note that we are passing the address of my_arr to a, that means we are using call by reference instead of call by value. So now both my_arr and a points to the same array. Inside the function, we are using for loop to increment every element of the array by 5. Since we are operating on the original array all the changes made here effect the original array.

1 thought on “Passing 1-D Array to a Function in C

  1. Thank you for the helpful example. I was wondering if it was an error that the function prototype new_array and the function definition my_func does not match.

Leave a Comment

%d bloggers like this: