C函数返回局部变量
本文介绍了C函数返回局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b) {
int c = a+b;
return c;
}
int main(int argc, char ** argv) {
int a = add(1, 2);
printf("%d\n", a);
return 0;
}
这里的c不是局部变量吗, 为什么还能从add函数返回呢?求教!
我的理解局部变量在函数调用结束后就会被释放, 比如下面这段代码:
#include <stdio.h>
#include <stdlib.h>
char *int_2_str(int value) {
char buf[20];
sprintf(buf, "%d", value);
return buf;
}
int main(int argc, char ** argv) {
char *buf = int_2_str(1024);
printf("%s", buf);
return 0;
}
编译器就会给出警告:
warning: address of stack memory associated with local variable 'buf' returned
解决方案
int add(int a, int b) {
int c = a+b;
return c;
}
這沒有問題, add返回的只是局部變量的值
char *int_2_str(int value) {
char buf[20];
sprintf(buf, "%d", value);
return buf;
}
這樣是危險 (但仍然合法) 的. int_2_str返回的是一個局部變量的地址, 而這個地址在函數結束後已經不知道是什麼內容了, 讀寫這個地址在大部分情況下沒意義且危險.
这篇关于C函数返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文