加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 本地变量保存相同的内存地址

发布时间:2020-12-16 10:49:46 所属栏目:百科 来源:网络整理
导读:以下程序打印两个不同变量的地址. #include iostreamusing namespace std;void f1(){ int i,k; cout"f1 : "iendl;}void f2(){ int j; cout"f2 : "jendl;}int main() { f1(); f2(); return 0;} Live demo 当我在GCC上运行这个程序时,我想知道,两个变量都有相
以下程序打印两个不同变量的地址.

#include <iostream>
using namespace std;

void f1()
{
    int i,k;
    cout<<"f1 : "<<&i<<endl;
}

void f2()
{
    int j;
    cout<<"f2 : "<<&j<<endl;
}

int main() {
    f1();
    f2();
    return 0;
}

Live demo

当我在GCC上运行这个程序时,我想知道,两个变量都有相同的地址.

为什么两个变量都保持地址相同?

编辑:

void f1()
{
    int i = 10;
    cout<<"f1 : "<<&i<<endl;
    cout<<"value of  : "<<i<<endl;
}

void f2()
{
    int j;
    cout<<"f2 : "<<&j<<endl;
    cout<<"value of j : "<<j<<endl;
}

int main() {
    f1();
    f2();
    return 0;
}

Live Demo 2

在这个例子中,如果我将值10分配给i,那么j也会打印10.我认为它无效,因为j未初始化.

解决方法

In that example,if I assigned value 10 to i then j also print 10. I
think it is not valid.

在此示例中,您没有使用c的任何内存分配概念.因此,您刚刚存储在i中的值将保留为从未从为i分配的内存中删除,然后当您调用fun2时,将为j分配相同的内存.这就是为什么你为这两个变量和同一个地址得到相同的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读