简体   繁体   中英

Different syntax of passing an array to a function in C++

#include <stdio.h>

void test2(int (&some_array)[3]){
  // passing a specific sized array by reference? with 3 pointers?
}

void test3(int (*some_array)[3]){
  // is this passing an array of pointers?
}

void test1(int (some_array)[3]){
  // I guess this is the same as `void test1(some_array){}`, 3 is pointless.
}

int main(){
  //
  return 0;
}

What is difference between the above 3 syntaxes? I have added comments to each section to make my questions more specific.

void test2(int (&some_array)[3])

This is passing a reference to an array of 3 int s, eg:

void test2(int (&some_array)[3]) {
    ...
}

int arr1[3];
test2(arr1); // OK!

int arr2[4];
test2(arr2); // ERROR!
 void test3(int (*some_array)[3])

This is passing a pointer to an array of 3 int s, eg:

void test3(int (*some_array)[3]) {
    ...
}

int arr1[3];
test3(&arr1); // OK!

int arr2[4];
test3(&arr2); // ERROR!
 void test1(int (some_array)[3])

Now, this is where things get a bit interesting.

The parenthesis are optional in this case (they are not optional in the reference/pointer cases), so this is equal to

void test1(int some_array[10])

which in turn is just syntax sugar for

void test1(int some_array[])
(yes, the number is ignored)

which in turn is just syntax sugar for

void test1(int *some_array)

So, not only is the number ignored, but also it is just a simple pointer being passed in. And any fixed array decays to a pointer to its 1st element, which means that any array can be passed in, even though the declaration suggests only 3 elements are allowed, eg:

void test1(int (some_array)[3]) {
    ...
}

int arr1[3];
test1(arr1); // OK!

int arr2[10];
test1(arr2); // ALSO OK!

int *arr3 = new int[5];
test1(arr3); // ALSO OK!
delete[] arr3;

Live Demo

In your code, test3 is the correct way of passing a pointer to an array, if that is what you want to.

void foo(int (*some_array)[3])
{
    for (size_t i = 0; i < 3; ++i) {
        printf("some_array[%zu]: %d\n", i, (*some_array)[i]);
    }
}

int main()
{
    int a[3] = { 4, 5, 6 };

    foo(&a);

    return 0;
}

Running this code returns what you'd expect:

some_array[0]: 4
some_array[1]: 5
some_array[2]: 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM