简体   繁体   English

在C ++中通过引用传递数组

[英]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 所以我有一个带有参数的函数: const char * str1
Now that argument passed is defined as: const char (&str1)[5] 现在,传递的参数定义为: 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. 您可以对任何数组使用相同的模式,但是类似char的数组的特殊好处是您可以使用字符串文字形式的文字数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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