伙计们,ptr如何获得之前的价值?代码很简单,我只是想知道它为什么不存储它在函数中分配的地址值.
#include<stdio.h>
#include<stdlib.h>
void test(int*);
int main( )
{
int temp;
int*ptr;
temp=3;
ptr = &temp;
test(ptr);
printf("\nvalue of the pointed memory after exiting from the function:%d\n",*ptr);
printf("\nvalue of the pointer after exiting from the function:%d\n",ptr);
system("pause ");
return 0;
}
void test(int *tes){
int temp2;
temp2=710;
tes =&temp2;
printf("\nvalue of the pointed memory inside the function%d\n",*tes);
printf("\nvalue of the pointer inside the function%d\n",tes);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
函数内指向的内存值:710
函数内指针的值:3405940
退出函数后指向的内存值:3
退出函数后指针的值:3406180
您按值传递了指针.
在里面的指针test是副本里面的指针main.对副本所做的任何更改都不会影响原件.
这可能会造成混淆,因为通过使用a int*,您将一个句柄("引用",实际上是一个引用是C++中存在的单独内容)传递给a int,从而避免了它的副本int.但是,指针本身就是一个对象,你可以按值传递它.
(您还试图将指针指向int该函数的本地指针test.使用它将无效.)