C/C++语言函数中参数的入栈顺序

对于函数,之前认为会用就行了,对其中的原理并不是很了解,就比如函数中参数的入栈顺序(在这说明一下,函数的参数是保存在栈中的,还有一些局部变量也是存放在栈中),这个问题来源于某互联网的面试题,当然答得很不好,查了很多大牛的博客做一下总结。

#include <iostream>
using namespace std;
void foo(int x,int y,int z){
    cout << &x << endl; //  0x28ff10
    cout << &y << endl; //  0x28ff14
    cout << &z << endl; //  0x28ff18
}

int main(){
    foo(1,2,3);
}

首先可以看出参数x,y,z 的地址从低到高,而栈的地址分配是从高到低,从而可以看出参数的入栈顺序使从右向左的,不过为什么要这样设计呢?通过查看各位大牛写的博客,自己做了一下总结:参数从右往左的入栈顺序的好处可以动态变化参数个数。如果自左向右的入栈方式,最前面的参数被压在栈底,除非知道参数个数,否则是无法通过栈指针的相对位移求得最左边的参数,这样就变成了最左边参数的个数不确定,正好和动态参数个数的方向相反。而这样设计的目的主要也是为了支持可变长参数形式。

不过在此我也提出一点疑问:这个是怎么支持动态变化参数的个数呢?可能提问的问题有点描述不清,还请见谅

选出一个确定的参数,确定参数类型,定位后续的参数

简单简述一下,具体见

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
(1) 堆栈的实现: ```C++ #include <iostream> using namespace std; const int MAXSIZE = 100; // 堆栈的最大容量 class Stack { private: char element[MAXSIZE]; int index; // 栈顶指针 public: Stack() { index = -1; } // 构造函数,初始化栈顶指针为-1 void push(char item); // 元素item进栈,即插入item到栈顶 void pop(); // 弹出栈顶元素 char top(); // 返回栈顶元素的值,但不移动栈顶指针 bool isEmpty(); // 判断堆栈是否为空 }; void Stack::push(char item) { if (index >= MAXSIZE - 1) { cout << "Stack is full!" << endl; return; } index++; element[index] = item; } void Stack::pop() { if (index < 0) { cout << "Stack is empty!" << endl; return; } index--; } char Stack::top() { if (index < 0) { cout << "Stack is empty!" << endl; return '\0'; } return element[index]; } bool Stack::isEmpty() { return (index == -1); } int main() { Stack s; s.push('a'); s.push('b'); s.push('c'); cout << s.top() << endl; // 输出c s.pop(); cout << s.top() << endl; // 输出b s.pop(); cout << s.top() << endl; // 输出a s.pop(); cout << s.top() << endl; // 输出Stack is empty!,并且返回'\0',表示栈已经为空 return 0; } ``` (2) 利用堆栈来检查一个C/C++语言程序的花括号、方括号和圆括号是否配对: ```C++ #include <iostream> #include <stack> #include <string> using namespace std; bool isMatching(char left, char right) { if (left == '(' && right == ')') return true; if (left == '[' && right == ']') return true; if (left == '{' && right == '}') return true; return false; } bool isValid(string s) { stack<char> st; for (int i = 0; i < s.length(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { st.push(s[i]); } else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { if (st.empty() || !isMatching(st.top(), s[i])) { return false; } st.pop(); } } return st.empty(); } int main() { string s = "{[(])}"; if (isValid(s)) { cout << "Valid!" << endl; } else { cout << "Invalid!" << endl; } return 0; } ``` 例子利用了STL的stack容器来实现堆栈。在遍历字符串时,如果遇到左括号,就将其压入堆栈;如果遇到右括号,就判断堆栈是否为空,如果为空或者栈顶的左括号与当前的右括号不匹配,则说明括号不配对,返回false。最后,如果堆栈为空,则说明所有括号都配对,返回true。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值