The problem of function return value in C language
There is a problem about the return value in the function in C language. the local variables in the function are mainly opened up on the stack, and the function variables are recycled. In view of the worthiness of function return, the following specific examples are given to illustrate:
The return value of a function is a local variable defined in the function
This type of return value can be used in the main function, because when returning a local variable is worth it, it is worth a copy, and that's all we need in the main function, so it's OK, for example.
Int fun (char * arr)
{
Int num = 0
While (* arr! ='\ 0')
{
Num = num * 10 + * arr -'0'
Arr++
}
Return num
Printf ("d", num)
}
Int main ()
{
Int tem = 0
Char * arr = "12345"
Tem = fun (arr)
Printf ("d", tem)
System ("pause")
Return 0
}
two。 The function returns the pointer variable defined in the function
Char * fun ()
{
Char * arr = "1234"
Return arr
}
Int main ()
{
Char * tem = fun ()
Printf ("% s", tem)
System ("pause")
Return 0
}
This is also correct in the process of running.
3. Function cannot return the address of a local variable
Int * fun ()
{
Int a = 10
Return & a
}
Int main ()
{
Int * tem = fun ()
Printf ("% d", * tem)
System ("pause")
Return 0
}
4. Function cannot return the first address of the array
Int * fun ()
{
Int arr [] = {1,2,3,4}
Return arr
}
Int main ()
{
Int * tem = fun ()
System ("pause")
Return 0
}