提问人:S Ali Mousavi 提问时间:6/7/2022 最后编辑:Vlad from MoscowS Ali Mousavi 更新时间:6/7/2022 访问量:109
在 c++ 中使用指针时出现奇怪的输出
Strange output when use Pointers in c++
问:
考虑以下 c++ 代码:
#include <iostream>
using namespace std;
int main() {
int x=2, y;
int *p = &x;
int **q = &p;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
*p = 8;
*q = &y;
std::cout << "--------------" << std::endl;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
return 0;
}
代码的输出是(当然列表编号不是输出的一部分):
- 0x7fff568e52e0
- 0x7fff568e52e8
- 2
- 2
- 0x7fff568e52e0
- '-----------'
- 0x7fff568e52e4
- 0x7fff568e52e8
- 0
- 8
- 0x7fff568e52e4
除了 7 和 9,所有输出都是我预期的。我很感激有人向我解释它们。
答:
2赞
Vlad from Moscow
6/7/2022
#1
变量未初始化y
int x=2, y;
所以它有一个不确定的值。
当指针指向指针时q
p
int **q = &p;
然后取消引用指针,你会得到一个对指针的引用。
所以这个赋值语句q
p
*q = &y;
其实相当于
p = &y;
也就是说,在赋值之后,指针包含变量的地址。p
y
所以这个电话
std::cout << p << std::endl;
现在输出变量的地址。y
- 0x7fff568e52e4
和这个电话
std::cout << *p << std::endl;
输出 that 的不确定值 happy 等于 0。y
9. 0
评论
y
y
*q = &y;
实际上与 because 别名(通过间接)相同。这意味着在代码过程中确实发生了变化(间接地,通过 )。p = &y;
*q
p
p
*q