C++指针给出数据类型为"int"的错误,但与"char"一起工作正常
C++ pointer gives error with data type 'int' but works fine with 'char'
我正在尝试学习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的指针地址。
有趣的东西。基本上只是四处乱搞,以获得指针之类的感觉。
相关文章:
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- Winpcap Findalldevs const char * 与 char * 不兼容
- 为什么 std::count 比 MSVC 编译器的普通循环慢,但与 GCC 相等?
- 将make_shared与 char[] 或 int[] 一起使用
- C - 与CHAR合作以及如何将其转换为整数(具有点的极端情况号)
- 使用 const char * 与 char * 创建自己的字符串
- 将动态阵列中的字符与char进行比较
- 将shared_ptr与char*一起使用
- C :使用函数过载与CHAR到INT之间的隐式转换,反之亦然
- 与 char c++ 上的按位 NOT 混淆
- Googletest 在 bazel test 中永远不会失败(在它应该失败的地方),但与 cmake & clion 一起工作
- 将MPI_Scatter与 char* 数组一起使用
- 左值没有模板匹配 (&&),但与模板匹配 (T &&)?
- 将字符串转换为char,当我cout时,它是正确的,但是当我将chdir与char一起使用时,它不起作用
- 使用与char的比较
- 为什么将forward_list与char一起使用要比将其与long-long一起使用优化得多
- Boost Spirit代码,可与msvc编译,但与gcc编译错误
- C++指针给出数据类型为"int"的错误,但与"char"一起工作正常
- 使用Windows函数SendMessage会导致与MSVC发生链接错误,但与MinGW不发生链接错误
- 如果它不是json,但与json类似,如何使用boost进行解析