Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Why Does C Treat Array Parameters as Pointers?

  • Difficulty Level : Easy
  • Last Updated : 25 Nov, 2021

In C, array parameters are treated as pointers mainly to,

  • To increase the efficiency of code
  • To save time

It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array.

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

The following two definitions of fun() look different, but to the compiler, they mean exactly the same thing. 

void fun(int arr[]) { 
    // body
}
// This is valid


void fun(int *arr) { 
    // body
}
// This is valid too

It’s preferable to use whichever syntax is more accurate for readability.



Note: If the pointer coming in really is the base address of a whole array, then we should use [ ].

Example: In this example, the array parameters are being used as pointers.

C




// C Program to demonstrate that C treats array parameters
// as pointers
#include <stdio.h>
 
void findSum1(int arr[])
{
    int sum = 0;
    for (int i = 0; i < 5; i++)
        sum = sum + arr[i];
    printf("The sum of the array is: %d\n", sum);
}
 
void findSum2(int* arr)
{
    int sum = 0;
    for (int i = 0; i < 5; i++)
        sum = sum + arr[i];
    printf("\nThe sum of the array is: %d \n", sum);
}
 
// Driver code
int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
 
    findSum1(arr);
    findSum2(arr);
    return 0;
}
Output
The sum of the array is: 15

The sum of the array is: 15 

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

My Personal Notes arrow_drop_up
Recommended Articles
Page :