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?