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); }
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:
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!