c++ - const char* 有什么异常(exception)吗?

标签 c++ string pointers ostream

如果cstring是一个指针,那为什么它可以直接取值呢?其次,为什么 ‍‍‍*cstring 的结果不等于整个字符串?第三,cstring是指向常量字符的非常量指针,为什么要改变它的值而不改变它的地址呢?

#include <cstdio>
#include <conio.h>
#include <iostream>

using namespace std;

int main() 
{
    const char* cstring = "string";
    cout << cstring << endl << *cstring << endl << &cstring << endl;

    cstring = "foo";
    cout << cstring << endl << *cstring << endl << &cstring << endl;

    _getch();
    return 0;
}

最佳答案

If cstring is a pointer, then why can it get a value directly?

operator <<cout对于 const char*专门以这种方式行事。它将指针视为以 NULL 结尾的字符串,并将打印它而不是指针值。对于不同的类型,您会得到不同的行为。对于 char*你打印了整个字符串。

Why wasn't the ‍‍‍*cstring's result equal to whole of string?

那是因为*cstring的类型是char再一次,operator <<只需打印一个字符即可正确运行。一个const char*本质上是一个char数组。数组本质上是一个指向数组第一个元素的指针。如果您使用 *指针上的运算符,您正在访问指针指向的任何内容。如果它指向第一个元素,那么,您将获得第一个元素。

Third, cstring is a non-constant pointer to a constant character, so why change its value and not change its address?

如您所说,cstring是指向常量数据的非常量指针。你不能改变它指向的地方(它是一个常量指针),但你可以用其他东西替换指向数据的内容。您指向相同的位置,但该单元格的内容发生了变化。

关于c++ - const char* 有什么异常(exception)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58130201/

相关文章:

string - 用空格解码base64

java - token 和行处理Java

c - 我应该使用什么 : strcpy or pointers?

c - 指针:尝试通过添加大量数字来取消引用指针时读取访问冲突

c++ - Tensorflow Op : how to include libtensorflow_framework. 所以?

python - 用于 C++ 和 Python 的轻量级密码学工具包

c++ - CPropertyPage::OnOK 中的数据交换完成了吗?

c++ - 使用 std::vector<T*> 是否不如 std::vector<shared_ptr<T>> 安全?

java - 使用每个元素之间的空格数分割行

c++ - 如何在 C++ 中使用指针创建输入法