C語言隨筆
@一般而言,區域變數會被存放在stack上,而stack在很多機器上都無法很大,這個時候的變通辦法就是將大容量的變數宣告成static的儲存類別,若是遞迴程式,則可能需要重新安排程式的架構了。
@Below is an example code from stack over flow, the subject is
@Below is an example code from stack over flow, the subject is
returning a local variable from function in C and return
here we get the warning as below:
"warning: function returns address of local variable"
#include <stdio.h>
int foo1(void)
{
int p;
p = 99;
return p;
}
char *foo2(void)
{
char buffer[] = "test_123";
return buffer;
}
int *foo3(void)
{
int t[3] = {1,2,3};
return t;
}
int main(void)
{
int *p;
char *s;
printf("foo1: %d\n", foo1());
printf("foo2: %s\n", foo2());
printf("foo3: %d, %d, %d\n", p[0], p[1], p[2]);
return 0;
}
And there's one guy has answer as below:
For
foo1(), you return a copy of the local variable, not the local variable itself.
For the other functions, you return a copy of a pointer to a local variable. However, that local variable is deallocated when the function finishes, so you end up with nasty issues if you try to reference it afterwards.
留言
張貼留言