gpt4 book ai didi

c++ - 在定义它的函数之外操作局部静态指针变量

转载 作者:太空狗 更新时间:2023-10-29 20:12:23 24 4
gpt4 key购买 nike

我想在全局范围内访问和修改定义在函数中的静态变量,但是输出的第2行和第3行是意外的,为什么ox是0?

#include <iostream>

using namespace std;

int * foo(){
static int *x = new int(5);
cout << *x << '\t' << &x << endl;
*x++;
return x;
}

int main(){
int * ox;
ox = foo();
cout << *ox << '\t' << &ox << endl;
*ox++;
cout << *ox << '\t' << &ox << endl;
int * t= foo();
}

输出是(在我的机器上):

5   0x6021d0
0 0x7fffdc82d3a0
0 0x7fffdc82d3a0
0 0x6021d0

欢迎任何评论。

最佳答案

操作顺序。执行两次 *ox++;

评估为(*ox)++ “增加指向的值”

它是*(ox++) “增加指针”

why ox is 0?

ox 恰好指向 0。您已将其递增以指向您不拥有的内存。

关于c++ - 在定义它的函数之外操作局部静态指针变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28037602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com