【发布时间】:2020-02-15 02:34:51
【问题描述】:
我了解到数组的名称用作指针。
在 C++ 中,当我创建整数类型数组名 'a' 时,cout a 会打印出数组的地址。
但是当我创建 char 类型数组名 's' 时,cout s 会打印出数组的内容而不是地址。
我想知道为什么会这样。
#include <iostream>
using namespace std;
int main()
{
// a string is a sequence of characters.
char s[4] = "abc"; // why not giving 3 as the size of the array?
// what if you want to print the address?
cout << '\n';
cout << (void*) s << "\n"; // Treat 's' as a void* variable.
cout<<(void*)&s<<endl;
cout << (void*)&s[0] << "\n"; // This also works.
cout << (void*)&s[1] << "\n";
cout<endl;
cout << s << "\n"; // Treat 's' as a void* variable.
cout<<&s<<endl;
cout << &s[0] << "\n"; // This also works.
cout << &s[1] << "\n";
return 0;
}
【问题讨论】:
-
我认为
cout使用了一个模板函数,它以不同的方式处理char数组。 -
关于“为什么不给 3 作为数组的大小”的问题 - 这是因为以空字符结尾的字符串
"abc"的长度为 4 个字符(预处理器隐含地添加了一个空字符)。 -
顺便说一下,对于静态声明的数组
x(即,其大小指定为常数),x和&x的值在技术上是相同的(相同的内存地址)。
标签: arrays pointers char integer