[英]Twos pointers reflects the same value but with different address( C language)
I created a function to return the pointer as follows:我创建了一个函数来返回指针,如下所示:
int* function(int cc){
int* p;
p=&cc;
return p;
}
int main(){
int a;
int *p1;
a=10;
p1=&a;
printf("value for *p1 = %d\r\n",*p1);
printf("value for *function %d\r\n", *function(a));
printf("pointer p1 = %p\r\n", p1);
printf("pointer function= %p\r\n", function(a));
return 0;
}
The console log is shown as follows:控制台日志如下所示:
value for *p1 = 10
value for *function 10
pointer p1 = 0x16d4bb1f8
pointer function= 0x16d4bb1dc
I really don't understand why two pointers could show the same value, but the address they stored are different.我真的不明白为什么两个指针可以显示相同的值,但是它们存储的地址却不同。
The variable you have passed in the function is done as a parameter (normal variable and not a pointer).您在函数中传递的变量是作为参数完成的(普通变量而不是指针)。 If you really want the it should work like you expect then you should pass pointer instead of a normal int local variable.
如果你真的想要它应该像你期望的那样工作,那么你应该传递指针而不是普通的 int 局部变量。
Make these changes:进行以下更改:
int* function(int *cc){
int* p;
p=cc;
return p;
}
int main(){
int a;
int *p1;
a=10;
p1=&a;
printf("value for *p1 = %d\r\n",*p1);
printf("value for *function %d\r\n", *function(&a));
printf("pointer p1 = %p\r\n", p1);
printf("pointer function= %p\r\n", function(&a));
return 0;
}
This code works and shows the output that you expect... We did this as we don't want a new copy of the variable passed into the function.此代码有效并显示您期望的输出......我们这样做是因为我们不希望将变量的新副本传递给函数。 We want the same address and so we should pass variable address in the function.
我们想要相同的地址,所以我们应该在函数中传递变量地址。
do this做这个
void function(int cc){
int* p;
p=&cc;
cc = 42; // just for fun
printf("value of cc inside function %d\r\n", cc);
printf("value of &cc %p\r\n", &cc);
}
int main(){
int a;
int *p1;
a=10;
p1=&a;
function(a);
printf("value for *p1 = %d\r\n",*p1);
printf("pointer p1 = %p\r\n", p1);
return 0;
}
you will see that cc is a copy of a, if you change its value inside 'function' it does not change 'a'.您会看到 cc 是 a 的副本,如果您在“function”中更改它的值,它不会更改“a”。 You have found c's 'call by value' semantics.
您已经找到了 c 的“按值调用”语义。 Meaning that variables are passed as copies to functions.
这意味着变量作为副本传递给函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.