gpt4 book ai didi

c++ - C++中字符和整数数组的不同行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:18 26 4
gpt4 key购买 nike

这是一个用 C++ 编写的小代码,其中我分别创建了两个 char 和 int 数据类型的数组。但是,对于这两个数组,相同的打印操作表现不同

#include<iostream>
using namespace std;
int main()
{
char a[5]={'h','e','l','l','o'};
int b[5]={1,2,3,4,5};

cout<<a; //displays the string "hello"
cout<<"\n"<<b; //displays the address of b[0]
return(0);
}

我希望输出是两个数组的第一个元素的地址,即分别是 a[0] 和 b[0] 的地址,但是在这种情况下 char 类型数组的行为不同。

最佳答案

这是 cout 的运算符 << 的特殊重载,它将 char * 参数视为空终止字符串并打印整个字符串。

如果要打印地址,请将其转换为 void *

cout << (void *) a;

关于c++ - C++中字符和整数数组的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56424790/

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