Home > Backend Development > C++ > Why does C treat array parameters as pointers?

Why does C treat array parameters as pointers?

王林
Release: 2023-09-08 13:17:02
forward
1458 people have browsed it

Why does C treat array parameters as pointers?

#C treats array parameters as pointers because it is less time consuming and more efficient. Although we could pass the address of each element of the array as a parameter to the function, doing so would be more time-consuming. So it's better to pass the base address of the first element to the function, for example:

void fun(int a[]) {
…
}
void fun(int *a) { //more efficient.
…..
}
Copy after login

Here is a sample code in C:

#include

void display1(int a[]) //printing the array content
{
   int i;
   printf("</p><p>Current content of the array is: </p><p>");
   for(i = 0; i < 5; i++)
      printf(" %d",a[i]);
}

void display2(int *a) //printing the array content
{
   int i;
   printf("</p><p>Current content of the array is: </p><p>");
   for(i = 0; i < 5; i++)
      printf(" %d",*(a+i));
}
int main()
{
   int a[5] = {4, 2, 7, 9, 6}; //initialization of array elements

   display1(a);
   display2(a);
   return 0;
}
Copy after login

Output

Current content of the array is:
4 2 7 9 6
Current content of the array is:
4 2 7 9 6
Copy after login

The above is the detailed content of Why does C treat array parameters as pointers?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template