我不明白以下内容:
int main() {
char ch[13] = "hello world";
function(ch);
return 0;
}
void function( char *ch) {
cout << ch;
}
这输出&#34; hello world&#34;。但是,如果我对指针ch进行解映射,则程序输出第一个字母,即&#34; h&#34;。我想出了原因。
cout << *ch;
答案 0 :(得分:3)
正如有人在评论部分中所说,解释指向数组的指针的结果是一个普通的char。
让我解释一下原因:
你的ch
指针指示了char数组开头的地址,所以当你调用cout<<ch
时,它会在屏幕上显示你从ch地址开始的所有内存中的所有内容并且顺序发送到第一个NULL
值出现并停止。
当您致电cout<<*ch
时,它将获取您存储在数组起始地址h
上的值。
解除引用意味着您从特定地址获取值。
希望它有所帮助! :)
答案 1 :(得分:1)
当您将数组直接或使用指向该数组的显式指针传递给函数时,它具有衰减功能,因为您无法在该函数上调用sizeof()
item,因为它实际上变成了一个指针。
因此,取消引用它并调用stream << operator的适当重载是完全合理的。
更多信息:https://stackoverflow.com/a/1461449/1938163
另请参阅以下示例:
#include <iostream>
using namespace std;
int fun(char *arr) {
return sizeof(arr);
}
int fun2(char arr[3]) {
return sizeof(arr); // It's treating the array name as a pointer to the first element here too
}
int fun3(char (&arr)[6]) {
return sizeof(arr);
}
int main() {
char arr[] = {'a','b','c', 'd', 'e', 'f'};
cout << fun(arr); // Returns 4, it's giving you the size of the pointer
cout << endl << fun2(arr); // Returns 4, see comment
cout << endl << fun3(arr); // Returns 6, that's right!
return 0;
}
或直接试用:http://ideone.com/U3qRTo