
栈:
在函数调用时,第一个进栈的是主函数中函数调用后的下一条指令(函数调用语句的下一条可执行语句)的地址,然后是函数的各个参数,在大多数的C编译器中,参数是由右往左入栈的,然后是函数中的局部变量。注意静态变量是不入栈的。
当本次函数调用结束后,局部变量先出栈,然后是参数,最后栈顶指针指向最开始存的地址,也就是主函数中的下一条指令,程序由该点继续运行。
堆:一般是在堆的头部用一个字节存放堆的大小。堆中的具体内容有程序员安排。
全文见百科
http://baike.baidu.com/view/93201.htm
#include <stdio.h>#include <stdlib.h>
#include <string.h>
struct CHAP5
{
char * pName
bool Gender
int Age
struct CHAP5 * next
}
struct Node_int{
int i
struct Node_int * next
}
/*由于两种栈在结构的高度相似性,用宏代替重复的语句进行栈 *** 作函数声明*/
#define DECLARE_STACK_PUSH(function_name, node_type) void function_name(node_type ** top, node_type * data) {\
node_type * x = (node_type *)malloc(sizeof(node_type))\
memcpy(x, data, sizeof(node_type))\
x->next = *top*top = xreturn }
#define DECLARE_STACK_POP(function_name, node_type) int function_name(node_type **top, node_type * data) {\
node_type * x = *topif (!x) return 0\
*top = x->nextmemcpy(data, x, sizeof(node_type))\
data->next = 0free(x)return 1}
/*这里才是真正声明四个栈 *** 作函数*/
DECLARE_STACK_PUSH(stack_int_push, struct Node_int)
DECLARE_STACK_POP (stack_int_pop, struct Node_int)
DECLARE_STACK_PUSH(stack_chap5_push,struct CHAP5)
DECLARE_STACK_POP (stack_chap5_pop, struct CHAP5)
void test_stack_int(void)
{
int x = 0struct Node_int y, * top = 0
printf("请输入一些数字检测堆栈,输入0结束\n")
do {
scanf("%d", &x)
y.i = x
stack_int_push(&top, &y)
}while(x)
printf("退栈结果:\n")/*相当于栈清空 *** 作*/
do {
x = stack_int_pop(&top, &y)
if (x) printf("%d\t", y.i )
}while(x)
printf("\n")
}
void test_stack_chap5(void)
{
int x = 0struct CHAP5 y, * top = 0
printf("请输入几个姓名、年龄、性别用于检测堆栈,年龄输入0表示结束\n")
do {
y.pName = (char *)malloc(64)
scanf("%s %d %d", y.pName , &(y.Age), &x)
y.Gender = x==0?true:false
stack_chap5_push(&top, &y)
}while(y.Age )
printf("退栈结果:\n姓名\t年龄\t性别\n")/*相当于栈清空 *** 作*/
do {
x = stack_chap5_pop(&top, &y)
if (x) printf("%s\t%d\t%s\n", y.pName , y.Age, y.Gender?"男":"女")
}while(x)
}
int main(void)
{
test_stack_int()
test_stack_chap5()
system("pause")
return 0
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)