从函数返回局部变量是否合法。 [英] Is it legal to return a local variable from function.
问题描述
大家好,
从函数返回局部变量是否合法。
问候
Hari >
Hi all,
Is it legal to return a local variable from function.
Regards
Hari
推荐答案
文章< 95 *********************** *********** @ d27g2000prf。 googlegroups.com>,
hari< ha ******** @ gmail.comwrote:
In article <95**********************************@d27g2000prf. googlegroups.com>,
hari <ha********@gmail.comwrote:
>是吗合法从函数返回局部变量。
>Is it legal to return a local variable from function.
你必须更加具体。你不能返回变量,只有
值。你当然可以返回局部变量的值。你没有
不能安全地返回一个指向本地变量的指针,因为它不会在返回后存在
。
- Richard
-
需要考虑多达32个字符
在一些字母表中 - 1963年的X3.4。
You''ll have to be more specific. You can''t return variables, only
values. You can certainly return the value of a local variable. You
can''t safely return a pointer to a local variable, because it won''t
exist after the return.
-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
文章
< 95 *************** ******************* @ d27g2000prf。 googlegroups.com>,
hari< ha ******** @ gmail.comwrote于2007年11月19日星期一下午4:57:
In article
<95**********************************@d27g2000prf. googlegroups.com>,
hari <ha********@gmail.comwrote on Monday 19 Nov 2007 4:57 pm:
大家好,
从函数返回局部变量是否合法。
Hi all,
Is it legal to return a local variable from function.
是的。然而,返回指向它的指针是危险的,除非所说的
本地是静态的。
Yes. Returning a pointer to it however is dangerous unless the said
local is static.
11月19日下午4:34 ,santosh< santosh .... @ gmail.comwrote:
On Nov 19, 4:34 pm, santosh <santosh....@gmail.comwrote:
文章
< 952875bd-9cc5-4cac-8ade- 6fa37cdb4 ... @ d27g2000prf.googlegroups.com>,
hari< haricib ... @ gmail.comwrote于2007年11月19日星期一下午4:57:
In article
<952875bd-9cc5-4cac-8ade-6fa37cdb4...@d27g2000prf.googlegroups.com>,
hari <haricib...@gmail.comwrote on Monday 19 Nov 2007 4:57 pm:
大家好,
从函数返回局部变量是否合法。
Hi all,
Is it legal to return a local variable from function.
是的。然而,返回指向它的指针是危险的,除非所述
local是静态的。
Yes. Returning a pointer to it however is dangerous unless the said
local is static.
好吧,我有一个疑问。如果我为本地指针分配内存并且
返回指向调用函数的指针的地址。现在这将是危险的
。例如:
int main()
{
char * test(int i);
char * tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s \ n",tmp);
免费(tmp);
返回0;
}
char * test(int i)
{
char * str =(char *)malloc(20);
sprintf( str,i value is:%d,i);
return str;
}
Well, I have a doubt. If I allocate memory for a local pointer and
return the address of the pointer to the calling function. Now will
this be dangerous. For eg:
int main()
{
char *test(int i);
char *tmp = NULL;
int i = 10;
tmp = test(i);
printf("%s\n", tmp);
free(tmp);
return 0;
}
char *test(int i)
{
char *str = (char*)malloc(20);
sprintf(str, "i value is: %d", i);
return str;
}
这篇关于从函数返回局部变量是否合法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!