C语言坑之局部变量

  1. 函数的动态(auto)变量是在栈存储的。栈存储的变量会在函数结束之后释放掉。
  2. 静态变量(static)是在数据区存储,进程结束之后,才会释放。

一.动态变量

main函数通过调用test函数,test函数接收了fun函数局部变量a的存储地址,但在接收之前,fun函数已经运行结束了,即局部变量a已经被释放掉了,所以test函数再访问a的时候,会提示段错误(编译时也会有警告)

#include <stdio.h>

void test(int *p)
{
  (*p)++;
}
int* fun()
{
  int a=5;
  return &a;
}
int main()
{
   int *p;
   p=fun();
   test(p);//fun函数已经结束
   printf("%d\n",*p);
   return 0;
}

main函数将局部变量a的存储地址传给test函数,因为在test函数运行时,main函数还未结束,所以test函数能够正常访问局部变量a。

#include <stdio.h>

void test(int *p)
{
  (*p)++;
}

int main()
{
   int a=5;
   test(&a);
   printf("%d\n",a);//输出6
   return 0;
}

二.静态变量

由于静态局部变量a是存储在数据区,即使fun函数已经结束了,但进程还未结束,所以test函数能够正常访问静态局部变量a。

#include <stdio.h>

void test(int *p)
{
  (*p)++;
}
int* fun()
{
  static int a=5;//静态局部变量
  return &a;
}
int main()
{
   int *p;
   p=fun();
   test(p);
   printf("%d\n",*p);//输出6
   return 0;
}
发布了17 篇原创文章 · 获赞 30 · 访问量 1816

猜你喜欢

转载自blog.csdn.net/qq_37451250/article/details/103794979
今日推荐