如何更改函数中参数的值

-1 c malloc

我试试看:

#include <stdio.h>
#include <malloc.h>

void foo(int* x)
{
   x = (int *)malloc(sizeof(int));
   *x = 5;
}

int main()
{

   int a;
   foo(&a);
   printf("%d\n",a);  //a = -858993460
   return 0;    

}
Run Code Online (Sandbox Code Playgroud)

为什么a!= 5的值.我在vs2010,Windows 7中运行此代码.

Sad*_*que 6

您正在通过malloc调用更改foo中的指针值 - 只需执行以下操作:

void foo(int* x)
{
   *x = 5;
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中 - 这个函数:

void foo(int* x)
{
   x = (int *)malloc(sizeof(int));
   *x = 5;
}
Run Code Online (Sandbox Code Playgroud)

工作原理如下:

+----+
| a  |
+----+
/
x points here
Run Code Online (Sandbox Code Playgroud)

然后你在x其他地方指出:

+----+                            +----+
| 5  | /* created by malloc*/     | a  |
+----+                            +----+
/ On Heap                         / On Stack
x now points here                a is now in memory somewhere not getting modified.
Run Code Online (Sandbox Code Playgroud)

而你做到了5.还要注意 - x是&a地址的本地副本a- 在C没有通过引用传递但只传递值的情况下 - 因为变量值被复制到函数中.