[英]Array shows different addresses, before and after being passed to a function by reference
I was curious to know why the addresses of the same array ie array b in my case is changing before and after it has been passed to the function manipulation(), as shown in the output picture. 我很想知道为什么相同数组(即我的数组b)的地址在传递给函数handler()之前和之后都会发生变化,如输出图片所示。
Please share your thoughts and help me figure this out.
请分享您的想法,并帮助我解决这个问题。 Thank you!
谢谢!
#include <stdio.h>
void manipulation(int *pa,int *pb){
int i;
for(i=0;i<10;i++){
*(pb+i)=*(pa+i);
printf("%d\t %04x\n",*pb+i,&pb+i);
}
}
int main(){
int a[10],b[10];
int i;
int *point;
point = &b[0];
printf("Enter the array elements\n");
for(i=0;i<10;i++){
scanf("%d\n",&a[i]);
}
for(i=0;i<10;i++){
printf("%04x\n",&point+i);
}
manipulation(&a[0],&b[0]);
return 0;
}
because you print ( address of your pointer) + i: 因为您打印(指针的地址 )+ i:
printf("%04x\n",&point+i);
printf("%d\t %04x\n",*pb+i,&pb+i);
you want to print the pointer + i: 您要打印指针+ i:
printf("%04x\n",point+i);
printf("%d\t %04x\n",*pb+i,pb+i);
Also you have a bug in there: 另外,您还有一个错误:
printf("%d\t %04x\n",*pb+i,pb+i);
*pb+i
is interpreted as (*pb) + i
that is the first value of the array plus i, or simply pb[0]+i
. *pb+i
被解释为(*pb) + i
,它是数组加i的第一个值,或者简称为pb[0]+i
。
you seem to get the right answer because your array is 1 2 3 ... 您似乎得到了正确的答案,因为您的数组是1 2 3 ...
you probably want this: 您可能想要这样:
printf("%d\t %04x\n",*(pb+i),pb+i);
or simply: 或者简单地:
printf("%d\t %04x\n",pb[i],pb+i);
Yeah, the real problems is comparing the address of point
to the address of pb
. 是的,真正的问题是将
point
的地址与pb
的地址进行比较。
Try using point + i
(or &point[i]
) and pb + i
(or &pb[i]
). 尝试使用
point + i
(或&point[i]
)和pb + i
(或&pb[i]
)。 I'm sure you will get the expected answer. 我相信您会得到预期的答案。
In case you are curious, &point + i
is the location in memory of the local variable point
plus the value of i
. 如果您感到好奇,则
&point + i
是局部变量point
在内存中的point
加上i
的值。 &pb + i
is the location in memory of the parameter pb
plus the value of i
. &pb + i
是参数pb
加i
的值在内存中的位置。 They are different variables, so they have different locations in memory. 它们是不同的变量,因此它们在内存中具有不同的位置。
point stores the address of array a. 点存储数组a的地址。 &point prints the address of point and adding 4 through out the loop.
&point打印点的地址,并在整个循环中加4。 same is the case with &pb.
&pb也是如此。 28fee8 is the place where point is stored and 28fed4 is the place where pb is stored.
28fee8是存储点的位置,而28fed4是存储pb的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.