我正在嘗試定義一個函式原型,它采用char不同長度的陣列。我知道我必須通過參考傳遞陣列,以避免陣列衰減到指向其第一個元素的指標。所以我一直在研究這個簡單的例子來讓我的理解正確。
#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;
}
這給了我編譯器錯誤:
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);
我認為函式簽名func(const char (&str)[len])指示指向char長度陣列的指標len,這就是我正在傳遞的內容func(&str)。
我試過func(str)了,我認為這是錯誤的,因為我傳遞的是值 str,而不是它的參考。但是,這實際上有效,我不明白為什么。
這里發生了什么?通過參考傳遞實際上意味著什么?
uj5u.com熱心網友回復:
您的函式已正確宣告,但您沒有正確地將陣列傳遞給它。
func(*str);首先將陣列衰減為指向第一個元素的指標,然后參考該指標,從而僅將第一個字符傳遞給func(). 但是沒有func(char)定義函式,所以這是一個錯誤。
func(&str);獲取陣列的地址,從而傳遞一個指向陣列的指標,而不是對它的參考。但是沒有func(char(*)[len])定義函式,所以這也是一個錯誤。
要通過str參考傳遞,您只需str按原樣傳遞,不帶*or &:
func(str);
這與將參考傳遞給任何其他型別的變數沒有什么不同,例如:
void func(int &value);
int i;
func(i);
附帶說明:printf(str);很危險,因為您不知道其中是否str包含任何%字符。更安全的呼叫是:
printf("%s", str);
要么:
puts(str);
但這些只有在str以空值終止的情況下才有效(在你的情況下)。更安全的是:
printf("%.s", (int)len, str);
不需要空終止符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454248.html
上一篇:我怎樣才能解決這個問題?“在正常塊后檢測到堆損壞。CRT檢測到應用程式在堆緩沖區結束后寫入記憶體”
下一篇:指標陣列對所有元素保持相同的值
