I am trying to define a function prototype which takes an array of char
of different lengths. I understand that I must pass the array by reference to avoid the array decaying to a pointer to its first element. So I've been working on this simple example to get my understanding correct.
#include <stdio.h> // size_t
//template to accept different length arrays
template<size_t len>
//pass array of char's by reference
void func(const char (&str)[len])
{
//check to see if the array was passed correctly
printf(str);
printf("\n");
//check to see if the length of the array is known
printf("len: %lu",len);
}
int main(){
//create a test array of chars
const char str[] = "test12345";
//pass by reference
func(&str);
return 0;
}
This gives me the compiler errors:
main.cpp: In function ‘int main()’:
main.cpp:19:14: error: no matching function for call to ‘func(const char (*)[10])’
func(&str);
^
main.cpp:6:6: note: candidate: template<long unsigned int len> void func(const char (&)[len])
void func(const char (&str)[len])
^~~~
main.cpp:6:6: note: template argument deduction/substitution failed:
main.cpp:19:14: note: mismatched types ‘const char [len]’ and ‘const char (*)[10]’
func(&str);
I thought that the function signature func(const char (&str)[len])
indicates a pointer to a char
array of length len
, which is what I am passing by func(&str)
.
I tried func(str)
, which I would expect to be wrong, since I am passing the value str, instead of its reference. However, this actually works and I dont understand why.
What is going on here? What does it actually mean to pass by reference?
CodePudding user response:
Your function is declared correctly, but you are not passing the array to it correctly.
func(*str);
first decays the array to a pointer to the 1st element, and then deferences that pointer, thus passing just the 1st character to func()
. But there is no func(char)
function defined, so this is an error.
func(&str);
takes the address of the array, thus passing a pointer to the array, not a reference to it. But there is no func(char(*)[len])
function defined, so this is also an error.
To pass str
by reference, you need to simply pass str
as-is without *
or &
:
func(str);
This is no different than passing a reference to a variable of any other type, eg:
void func(int &value);
int i;
func(i);
On a side note: printf(str);
is dangerous, since you don't know if str
contains any %
characters in it. A safer call would be either:
printf("%s", str);
Or:
puts(str);
But those only work if str
is null-terminated (which it is in your case). Even safer would be:
printf("%.s", (int)len, str);
Which doesn't require a null terminator.