如何在函数中更改参数的值 [英] How to change value of arguments in the function

查看:127
本文介绍了如何在函数中更改参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试:

#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;    

}

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

why the value of a != 5 . i run this code in vs2010 ,windows 7.

推荐答案

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

You are changing the pointer value in foo by the malloc call - just do this:

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

在您的代码中-此功能:

In your code - this function:

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

工作原理如下:

+----+
| a  |
+----+
/
x points here

然后将x指向其他位置:

+----+                            +----+
| 5  | /* created by malloc*/     | a  |
+----+                            +----+
/ On Heap                         / On Stack
x now points here                a is now in memory somewhere not getting modified.

然后将其设置为5.还要注意-xa&a地址的本地副本-在C中没有按引用传递,而仅按值传递-因为变量值已复制到函数中.

And you make it 5. Also note - x is a local copy of the &a address of a - in C there is no pass by reference but only pass by value - since the variables value is copied into the function.

这篇关于如何在函数中更改参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆