C程序以查找堆栈的增长方向

堆栈是一种存储元素的数据结构。堆栈上有两个操作。推送,将新元素添加到堆栈中。从堆栈中删除元素的pop。

堆栈可以根据使用它的程序的性质向上和向下增长。该程序在程序中查找堆栈增长的方向。

算法

Step 1: Create a local variable in the main function.
Step 2: Create a function that with a local variable.
Step 3: Call the function from the main function. And then compare the local variables of in both these functions.
Step 4: Compare the address of local variables in main and the function.
Step 5: If address variable in main is more than local variable of the function, then stack grows upward otherwise it grows downward.

示例

#include<stdio.h>
void fun(int *main_local_addr){
   int fun_local;
   if (main_local_addr < &fun_local)
      printf("Stack grows upward\n");
   else
      printf("Stack grows downward\n");
}
int main(){
   int main_local;
   fun(&main_local);
   return 0;
}

输出结果

Stack grows downward