gpt4 book ai didi

c++ - 理解字符引用

转载 作者:可可西里 更新时间:2023-11-01 15:47:43 25 4
gpt4 key购买 nike

我编写了这个简单的脚本来理解引用是什么,但我被 char 数组卡住了。

int numbers[5] = {3, 6, 9, 12, 15};

for (int i = 0; i < 5; i++)
{
cout << numbers[i] << endl;
cout << &numbers[i] << endl;
}

cout << "--------------" << endl;

char letters[5] = {'a', 'b', 'c', 'd', 'e'};

for (int i = 0; i < 5; i++)
{
cout << letters[i] << endl;
cout << &letters[i] << endl;
}

这是输出:

3
0xbffff958
6
0xbffff95c
9
0xbffff960
12
0xbffff964
15
0xbffff968
--------------
a
abcde
b
bcde
c
cde
d
de
e

对于 int 数组,当我使用 &numbers[i] 时,我收到一个奇怪的数字,它是一个内存位置。还行吧;这正是我所理解的。

但是对于 char,我不明白为什么我有这个输出。

最佳答案

原因是 cout“知道”如何处理 char * 值 - 它将字符串打印为以 NUL 结尾的 C 字符串。

int * 值并非如此,因此 cout 打印指针值。

您可以通过强制转换强制输出指针值:

cout << static_cast<void *>(&letters[i]) << endl;

关于c++ - 理解字符引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9253832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com