C++指针给出数据类型为"int"的错误,但与"char"一起工作正常

C++ pointer gives error with data type 'int' but works fine with 'char'

本文关键字:但与 char 一起 工作 错误 指针 数据类型 int C++      更新时间:2023-10-16

我正在尝试学习C++中的指针和引用。我有以下程序。

#include <iostream>
using namespace std;
int main() {
    // 1st statement / code of block. This portion works fine.
    char *str = "A";
    cout << str << endl;   // it outputs A
    cout << *str << endl;  // it outputs A
    cout << &str << endl;  // it outputs 0x23fe40 (memory location)
    char **b = &str; 
    cout << b << endl;   // it outputs 0x23fe40 (memory location)
    cout << *b << endl;  // it outputs A

    // 2nd statement / code of block. This portion gives error.
    // int *st = 5;
    // cout << st << endl;
    // cout << *st << endl;
    // cout << &st << endl;
    // int **c = &st;
    // cout << c << endl;
    // cout << *c << endl;    
    return 0;
}

代码在此阶段运行良好。但是我运行了第二条语句(我在这里评论了它),编译器给出了以下错误。

Invalid conversion from 'int' to 'int*'

有人能解释一下为什么会这样吗?两个语句几乎相同,唯一的区别是我在第二个语句中使用了数据类型"int"。是因为数据类型不同吗?

正如人们之前提到的,使用str可以隐式创建一个字符数组,返回的*char指针指向内存中的该数组。因此,当你取消引用它时,你会得到字母"A"。

你应该意识到的一件事是,当你取消引用一个字符串时,你只会得到数组中的第一个字符(返回的指针指向数组的第一个值)。如果字符串是"AB"而不是"A",*str将只返回"A"。其中as-str将打印出"AB"。

这对整数变量不起作用,因为变量初始化时没有隐式引用。整数是基元,没有引用就不能取消引用,没有指向的指针就不能检索指针。这就是它无法将整数值转换为指向整数值的指针的原因。

请注意,您仍然可以声明一个包含基元值的变量并获取其地址(声明后&st仍然有效)。如果你想用int值取消内存引用,你可以随意引用其他变量。例如

int i = 5;
int *st = &i;
int **c = &st;

第一个变量将打印出5,第二个将打印出变量i的地址,第三个将打印变量i的指针地址。

有趣的东西。基本上只是四处乱搞,以获得指针之类的感觉。