关于函数参数传递之我的理解

Bai_Yuanyong 2006-03-20 06:07:25
一个函数如果不是传递指针,那么在实际调用过程中会生成一个临时变量替代这两个传入的参数:

#include <stdio.h>

void add(int a, int b)
{
printf("the address of a and b is: %x %x\n",&a,&b);
}

int main()
{
int a=100, b=1;
printf("the address of a and b is: %x %x\n",&a,&b);
add(a,b);
}

==================================================================
the address of a and b is: 22ff74 22ff70
the address of a and b is: 22ff50 22ff54

可以看到实际的参数已经被替代了。
那么如果传递指针的情况下又是什么样的呢?

#include <stdio.h>

void add(int *a, int *b)
{
printf("the content of a and b is: %x %x\n",a,b);
printf("the address of a and b is: %x %x\n",&a,&b);
}

int main()
{
int x=100, y=1;
int *a=&x, *b=&y;
printf("the content of a and b is: %x %x\n",a,b);
printf("the address of a and b is: %x %x\n",&a,&b);
add(a,b);
}

==============================================================
the content of a and b is: 22ff74 22ff70
the address of a and b is: 22ff6c 22ff68
the content of a and b is: 22ff74 22ff70
the address of a and b is: 22ff40 22ff44

可以看到实际传递的指针也被两个临时的指针替代了,但是指针所指的地址没有改变。
所以我们在函数内对指针所指向的地址做的修改不会对实际的传入的指针所指地址造成修改,但是如果对所指内容做修改则会修改相应的实际数据。

在C++中又看到这样的话:
如果参数是指针,且仅作输入用,则应在类型前加const,以防止该指针在函数体内被意外修改。
例如:
void StringCopy(char *strDestination,const char *strSource);

在我们加了const之后则没有办法对所指内容做修改,否则会出现编译错误,但是我们还是可以改变指针指向地址,这已经无所谓了,实际的指向地址是不会改变的。

认识到所有的传入参数都会在编译器中为它分配一个临时copy
...全文
65 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧