简体   繁体   中英

Passing array by reference in C++

this might sound a very basic question, however i am having little confusing understanding this piece of code:

so i have a function that takes argument: const char * str1
Now that argument passed is defined as: const char (&str1)[5]

I would appreciate if you could elaborate a little how the character pointer array is defined in 2nd line?

EDIT:

template<unsigned N, unsigned M>
int compare(const char (&p1)[N], const char (&p2)[M]){
   return strcmp(p1,p2);
}

I am trying to understand how the non type parameter which is essentially translating to character string is defined here

Nothing is "essentially translating". The function template expects to be called with two array arguments.

char s[] = { 'a', 0, 'c' };

compare(s, "xyz");    //  first argument "s" is a named array, N = 3
                      //  second argument is a string literal, M = 4

You can use the same pattern for any array, but the special benefit for char-like arrays is that you can have literal arrays in the form of string literals.

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