Sayalic
Sayalic

Reputation: 7650

How to understand foo(char (&p)[10])?

#include <iostream>

void foo(char (&p)[10]) {
    printf("%d\n", sizeof(p));
}

char p[10] = "aaa";

int main() {
    foo(p);
}

that code output 10, but I can't understand.

What is the meaning of char (&p)[10] here?

Upvotes: 2

Views: 168

Answers (3)

Zegar
Zegar

Reputation: 1015

When the specifics of your application area call for an array of specific fixed size (array size is a compile-time constant), one of the ways to pass such an array to a function is by using a pointer-to-array parameter

void foo(char (*p)[10]);

in your case you have very similar situation but done by a reference:

void foo(char (&p)[10]);

That's all.

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114440

The argument to the function foo is a reference (&) to a char array of 10 elements (char ... [10]). The name of the argument is p. Reference means that you specify the argument as-is (no pointer or address needed), so calling foo(p) in main is the correct way to do it given how p is declared. The function foo always prints 10 because its argument is 10 bytes in size.

Upvotes: 1

Yam Marcovic
Yam Marcovic

Reputation: 8141

foo() is declared as a function that specifically gets a reference to a char array of size 10, without any array-to-pointer conversions taking place.

Since sizeof(char) is 1, then sizeof(char[10]) is 10. That's why your program prints 10.

Upvotes: 2

Related Questions