c语言中有关于在函数返回值的问题,在函数中的局部变量主要是在栈上开辟的,出了函数变量就被回收了,针对函数返回值得问题,给出下面几个比较具体的例子来说明:

  1. 函数返回值是在函数中定义的局部变量

    这类型的返回值在主函数中是可以使用的,因为返回局部变量值得时候,返回的是值得一个副本,而在主函数中我们需要的也只是这个值而已,因此是可以的,例如


  2. int fun(char *arr)

  3. {

  4. int num = 0;

  5. while (*arr != '\0')

  6. {

  7. num = num * 10 + *arr - '0';

  8. arr++;

  9. }

  10. return num;

  11. printf("%d ", num);

  12. }

  13. int main()

  14. {

  15. int tem = 0;

  16. char *arr = "12345";

  17. tem = fun(arr);

  18. printf("%d",tem);

  19. system("pause");

  20. return 0;

  21. }

  22. 2.函数返回的是函数中定义的指针变量

  23. char *fun()

  24. {

  25. char *arr = "1234";

  26. return arr;

  27. }

  28. int main()

  29. {

  30. char *tem = fun();

  31. printf("%s", tem);

  32. system("pause");

  33. return 0;

  34. }

  35. 这在运行过程中也是正确的。

  36. 3.函数不能返回局部变量的地址

  37.  

  38. int *fun()

  39. {

  40. int a = 10;

  41. return &a;

  42. }

  43. int main()

  44. {

  45. int *tem = fun();

  46. printf("%d", *tem);

  47. system("pause");

  48. return 0;

  49. }

  50. 4.函数也不能返回数组的首地址

  51.  int *fun()

  52. {

  53. int arr[] = { 1, 2, 3, 4 };

  54. return arr;

  55. }

  56.  int main()

  57.  {

  58. int *tem = fun();

  59. system("pause");

  60. return 0;

  61. }