Home > Backend Development > C++ > How to Pass an Array by Reference in C ?

How to Pass an Array by Reference in C ?

DDD
Release: 2024-12-27 07:51:10
Original
744 people have browsed it

How to Pass an Array by Reference in C  ?

Passing an Array by Reference

In C , passing an array by reference allows us to modify the original array that was passed to the function. When we use the ampersand (&) sign before an array type, we create a reference to that array.

Consider the following code:

void foo(int (&myArray)[100])
{
}

int main()
{
    int a[100];
    foo(a);
}
Copy after login

In this example, the foo function accepts a reference to an array of 100 integers. The brackets after myArray are necessary to indicate that the parameter is an array reference, not a pointer.

The expression (&myArray)[100] means "a reference to an array of 100 integers." It is an alternative way to declare an array reference. The following declarations are equivalent:

  • int (&myArray)[100]
  • int *myArray
  • int myArray[]

When passing an array by reference, the compiler treats the function parameter as a pointer to the first element in the array. This means any changes made to the array in the function will also be reflected in the original array.

It's important to note that void foo(int (&myArray)[100]) only accepts arrays of 100 elements. If we attempted to pass an array with a different size to the foo function, it would result in a compile-time error.

The above is the detailed content of How to Pass an Array by Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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