为什么char*和int*的行为不同

Dev*_*wal 0 c++ int pointers char

下面给出的程序有一些疑问.任何讨论都有助于理解内部.

#include <iostream>
using namespace std;

int main() {
    // your code goes here

    char* ptr = new char[11];
    ptr = "helloworld";
    cout << ptr;

    int* ptr1 = new int[2];
    //ptr1 = {12, 24};
    cout << ptr1;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  1. cout << ptr; 打印helloworld(打印价值); cout << ptr1打印地址而不是值.为什么??
  2. 自从cout << ptr; 打印值,如何获取新char [11]分配给ptr的地址.
  3. 如果ptr ="helloworld"; 被允许.为什么ptr1 = {12,24}; 不被允许?

Dwe*_*rly 6

你的问题的核心是为什么<<运算符在一个case中输出一个字符串而在另一个case中输出一个地址.这是来自它的c语言遗产,其中没有"真正的"字符串类型.在c/c ++中,char*和char []被唯一地处理,通常被假定为'字符串'.假定其他类型的数组是该类型的数组.因此,在输出char*时,<<假设您需要一个字符串输出,而使用int []时,它会输出数组的地址而不是它的内容.简单地说,char []和char*在许多输出函数中被视为特殊情况.

我可以看到你对编译器处理源代码的方式也有一些困惑.考虑:

char* ptr = new char[11];
ptr = "helloworld";
Run Code Online (Sandbox Code Playgroud)

此代码分配11个内存的char并将ptr设置为该分配的地址.下一行创建一个常量"helloworld",它被分配和初始化,并将ptr设置为该内存的地址.你有两个内存位置,一个有11个未初始化的字符,一个初始化为"helloworld\0".