Passing Arrays as Arguments
For Complete YouTube Video: Click Here
In this class, we will understand Passing Arrays as Arguments.
We have already discussed the concepts of passing integers as arguments and assigning them to the pointers.
Table of Contents
Passing Arrays as Arguments
To understand this, we will consider two examples.
Example 1
The image below is example 1.
In the above example, we have defined an array of five elements and a function f with an integer pointer parameter.
In the second line of the program, we call function f with arguments as the address of a.
The address of a is the starting address of the array, which is 100.
Now the address of a will get assigned to pointer p.
Now p is referencing the array a.
All the elements in the function’s body will get updated and returned to the called ‘function.’
The for loop in the ‘main’ function will print all the elements of the array a.
The for loop is not having the body, so which statements will get executed.
So far, in our previous classes, we have given open and closed flower braces for the loop’s body.
But in our example, we don’t have that, in such cases, only one statement below the for loop is considered as the loop’s body.
If we pass an array as the argument, we have to assign it to a pointer.
Example 2
The image below is example 2.
In the above example, we have defined an array of five elements and a function f with an integer pointer parameter.
The critical point to understand here is a++ in the second line of the ‘main’ function.
As we all know the a++ means a = a + 1.
Is it possible to do such kind of operation on an array?
It is not possible because an array is not a variable, and the compile will generate an error. An array is a mnemonic.
Mnemonic means it is just addressed, not the name as that of a variable.
a = a + 1 means 100 = 100 + 1 for the compiler.
The ‘lvalue’ for the assignment should always be a variable, but here it is an address.
Throughout the program, wherever we use the array’s name, it is just the starting address.
But in the function f, we have used p++, which is accepted because the pointer is a variable.
The concept in this example is essential to understand.