arrays - 数组名作为指针
问题描述
我了解到数组的名称用作指针。
在 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;
}
解决方案
1.始终字符串常量以 null('\0') 值结尾。如果你不想要这个 Null 值,你可以像下面这样赋值
字符 s1[3] = {'a','b','c'};
2.上面的语句你正在做显式类型转换!您正在将 char 数组转换为 void 指针。而 WKT,char 的大小为 1。所以地址增加了 1。仅供参考,数组名称的表示法,例如's'等于&s [0]。(第一个索引的地址),它也等于数组名称的地址(&s)。
[s == &s == &s[0]]
- 而且我们知道,一个void指针可以保存任何类型的地址,并且可以被类型转换为任何类型。但是在将字符转换为void指针时,我们只看到地址转换。因为 &s 和 s 只保存第一个字符的地址。此外,cout 不会识别该值是字符值。
推荐阅读
- c# - 阅读窗格和撰写窗口上的 Outlook VSTO 自定义任务窗格?
- flutter - 是他们在颤动中禁用延迟加载的一种方法
- coq - 在 Coq 中建模有限集的基数
- python - 如何使用python比较具有字典列表的两个字典元素
- python-3.x - 在 tkinter 的函数中使用 os 模块遍历列表时卡在 for 循环中
- arrays - 在 Vuejs 中渲染数组
- php - 删除字符串中术语的第一个实例 - 不区分大小写
- c - 无法访问由 realloc 分配的内存
- r - 为什么希腊字母无法在 R (v4) PDF 输出中呈现?
- jsr363 - 如何确定 javax.measure.Quantity 是否是速度?