#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
這沒有問題, add返回的只是局部變量的值
這樣是危險 (但仍然合法) 的. int_2_str返回的是一個局部變量的地址, 而這個地址在函數結束後已經不知道是什麼內容了, 讀寫這個地址在大部分情況下沒意義且危險.