如何查看变量的内存地址位于哪个区?

如何查看变量到底存储在了哪个区?

通过对进程内存分区的学习,了解到了进程的四大内存分区:代码区、全局区、堆区和栈区,那么程序中的某个变量,怎么判断或者查看它到底存储在了哪里?
参考
通过命令行进行查看,命令:ps -aux
在这里插入图片描述其中PID为进程号,我们后续将根据进程号进行查看。
rw -p为权限,表示读写。
搜索在堆的内存地址,通过打印变量的内存地址,与之对比,即可知道该变量位于堆上还是栈上。
在这里插入图片描述

以源程序stack_4.cpp为例

// 后缀表达式(逆波兰表达式)
#include <iostream>
#include <string>
#include <stack>
using namespace std;

int caculate(string &notation)
{
    // 1 创建一个栈对象oprands存储操作数
    stack<int> oprands;
    int result = 0;
    // 2 从左往右遍历表达式,如果为操作数就入栈,如果是运算符,就从栈中弹出两个操作数进行计算,并将计算结果压入栈中
    for (int i = 0; i < notation.length(); i++)
    {
        char current = notation[i];
        cout<<notation[i]<<endl;
        int o1, o2;

        switch (current)
        {
        case '+':
            o1 = oprands.top();
            oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
            o2 = oprands.top();
            oprands.pop();
            result = o2 + o1;
            oprands.push(result);
            break;
        case '-':
            o1 = oprands.top();
            oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
            o2 = oprands.top();
            oprands.pop();
            result = o2 - o1;   //o1-o2的后缀表达式为o1 o2 -,出栈顺序为o2 o1,除法同理
            oprands.push(result);
            break;
        case '*':
            o1 = oprands.top();
            oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
            o2 = oprands.top();
            oprands.pop();
            result = o2 * o1;
            oprands.push(result);
            break;
        case '/':
            o1 = oprands.top();
            oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
            o2 = oprands.top();
            oprands.pop();
            result = o2 / o1;
            oprands.push(result);
            break;
        default:
            oprands.push(current);
            break;
        }
    }
    result = oprands.top();
    return result;
}

int main()
{
    string test = "352-*7+";
    cout << "test = 352-*7+ = " << caculate(test) << endl;
    getchar();	//!注意暂停,否则程序执行到return 0之后将结束进程
    return 0;
}

编译执行:
在这里插入图片描述

注意不要回车,打开一个新的命令行终端:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值