gpt4 book ai didi

c++ - char* str ="ab", str 和 &str 的混淆

转载 作者:太空宇宙 更新时间:2023-11-04 05:25:15 28 4
gpt4 key购买 nike

我正在学习指针,这是我的代码。我定义了一个指向 char(实际上是字符串)的指针 *str 和一个指向 int *a 的指针,它们的定义方式相同。我认为 stra 都应该是一个地址,但是当我试图输出 str&str 时,a&a,我发现str不是地址,是字符串。就stra的类型而言,char *str和int *a有什么区别?谢谢。

#include<iostream>
#include<string>
using namespace std;
int main()
{
char *str = "FA";
cout << "str: " << str << endl;
cout << "&str: " << &str << endl;

int b = 5;
int *a = &b;
cout << "a: " << a << endl;
cout << "&a: " << &a << endl;
}

这是输出:

str: FA
&str: 0x7fff5a627280
a: 0x7fff5a62727c
&a: 0x7fff5a627288

最佳答案

好吧,这归结为 C 语义。字符串不是 C 中定义的类型。char单个字符的类型。为了在 C 中处理字符串,按照约定指向 char 的指针表示从该指针指向的位置开始到第一个 0 结束的字符串字节。

为了说明这一点:

char *str = "ABC";

“翻译”成类似的东西

const char <nosymbol>[4] = {'A', 'B', 'C', '\0'};
char *str = &(<nosymbol>[0]);

C++ 知道 char * 的这种特殊含义所以,<<运算符将遵循 C 程序员的最小意外原则,取 char *作为一个字符串。

关于c++ - char* str ="ab", str 和 &str 的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466794/

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