Introduction
An array is a data structure used to store multiple values in a single variable instead of declaring separate variables for each value. A variable stores the memory address of another variable as its value, called a pointer. A pointer variable points to a data type (like int ) of the same type and is created with the * operator. In this article, we will discuss why C treats array parameters as pointers.
You can also read about the dynamic arrays in c and C Static Function.
Why does C treat array parameters as pointers?
In the programming language of C, it has been observed that it treats array parameters as pointers. In C, the array name acts as a pointer and can be passed to function. When an array is passed as a parameter to a function, it doesn’t create a copy of the array. Rather the array parameter/ array name acts as a pointer that points to the base address or the first element, i.e., the element present at the 0th index of the array. This feature in C increases the coding efficiency and saves time and space. In most cases, the passing of an array to a function is done so that the function can access and modify the array elements in place without creating a copy of the whole array, which is inefficient and takes extra space and time.
void ninja(int arr[]) {
}
void ninja(int *arr) {
}
In the above code, both the function definitions are valid, and in both cases, the array parameters behave like a pointer.
Take, for example:
void printEven1(int arr[]){
int i;
printf("\n Even elements in the array are: \n");
for(i=0;i<6;i++)
printf(" %d",a[i]);
}
void printEven2(int *arr){
int i;
printf("\n Even elements in the array are: \n");
for(i=0;i<6;i++)
printf(" %d",*(arr+i));
}
void main(){
int a[5] = {1,2,3,4,5,6};
printEven1(arr);
printEven2(arr);
}
Output
Even elements in the array are:
2 4 6
Even elements in the array are:
2 4 6
You can implement it by yourself on c online compiler.