qq_29879731 2017-06-30 03:22 采纳率: 0%
浏览 929

关于局部变量内存分配以及static关键字的问题

#include
#include
#include
using namespace std;
void test2(int count) {
printf("%d count:%d\n", this_thread::get_id(), count);
int ef[count];
int d[5];
printf("%d %d %p %d\n",this_thread::get_id(), count, d, sizeof(d));
static int a[5];
printf("%d %d %p %d\n", this_thread::get_id(), count, a, sizeof(a));
int b[5];
printf("%d %d %p %d\n", this_thread::get_id(), count, b, sizeof(b));
sleep(5);
}
void test() {
int count = 1;
while(count+=100){
test2(count);
}

}
int main() {
printf("Hello world!\n");
thread t1(test);
thread t2(test);
t1.join();
t2.join();
return 0;
}
我的编译器里这份代码中a,b,d的地址始终不变,理论上来说不应该不变呀,这应该是编译器的优化吧?
还有,我就是觉得static变量其实是在编译器就分配内存并不作改动,想验证这个,结果发现不止static变量地址不会变化普通定长数组地址也不改动,那岂不是很尴尬么。。。。我觉得我的想法是对的,因为static变量在不同线程中也不同,另一方面,百度发现确实这样。。。。
我的电脑上运行结果如下:
Hello world!
-990759168 count:101
-990759168 101 0x7f9fc4f22de0 20
-990759168 101 0x604180 20
-990759168 101 0x7f9fc4f22e00 20
-999151872 count:101
-999151872 101 0x7f9fc4721de0 20
-999151872 101 0x604180 20
-999151872 101 0x7f9fc4721e00 20
-990759168 count:201
-990759168 201 0x7f9fc4f22de0 20
-990759168 201 0x604180 20
-990759168 201 0x7f9fc4f22e00 20
-999151872 count:201
-999151872 201 0x7f9fc4721de0 20
-999151872 201 0x604180 20
-999151872 201 0x7f9fc4721e00 20
-990759168 count:301
-990759168 301 0x7f9fc4f22de0 20
-990759168 301 0x604180 20
-990759168 301 0x7f9fc4f22e00 20
-999151872 count:301
-999151872 301 0x7f9fc4721de0 20
-999151872 301 0x604180 20
-999151872 301 0x7f9fc4721e00 20

  • 写回答

3条回答 默认 最新

  • threenewbee 2017-07-01 16:24
    关注

    相同的代码,相同的编译选项,在相同的编译器上编译,静态变量地址不变很正常。

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog