我的 pointer/addresses 无论如何都错了
My pointer/addresses are wrong no matter what I try
这是我正在尝试的:
int a,b;
int *ptr;
a = 123;
ptr = &a;
b = *ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("&ptr is %p\n",&ptr);
printf("&b is %p\n",&b);
结果:
&a is 0x7ffee01fc828
ptr points to 0x7ffee01fc828
&ptr is 0x7ffee01fc818
&b is 0x7ffee01fc820
我希望 &b 显示与 &a 相同的地址...但事实并非如此,所以我尝试了:
int a,*b;
int *ptr;
a = 123;
ptr = &a;
b = ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("&ptr is %p\n",&ptr);
printf("&b is %p\n",&b);
这仍然会导致 &b:
的意外内存地址
&a is 0x7ffee1cbd828
ptr points to 0x7ffee1cbd828
&ptr is 0x7ffee1cbd818
&b is 0x7ffee1cbd820
谁能帮我理解为什么我无法获得与 &ptr 或 &a 匹配的相同地址的 &b?
谢谢!
现在 a
、b
和 ptr
是 3 个不同的变量(无论其类型如何)
所以他们的地址是不同的。通过 not 获取指针变量的 address,您将获得相同的值。
int a,*b;
int *ptr;
a = 123;
ptr = &a;
b = ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("b is %p\n",b);
I expected &b to show the same address as &a…
有这种期望意味着您对指针如何工作以及它们在 C 编程语言中的语义有什么错误的心理模型。关键的误解似乎发生在原始代码片段的这两行:
首先你有
b = *ptr;
这一行转换为 *"copy the contents of the memory at address ptr
into the variable b
." 变量 b
甚至从未接触过指针本身。您可以将它完美地重写为相同的效果
int tmp = *ptr;
b = tmp;
事实上,每个现代 C 编译器都会为这两种情况生成相同的代码。
你误会的第二行就是这一行
printf("&b is %p\n",&b);
特别是取变量b
地址的效果,即&b
的结果。 b
是一个完全独立的变量,有自己的地址。 无法更改此地址! 变量唯一可以更改的是它的值。
指针也是变量,是的,指针本身确实有一个地址。指针的值是它指向的地址。但是像每个变量一样,您不能更改存储变量的地址,并且当您将地址分配给指针时,您正在更改它的值。因此,当您在第二个代码片段中分配 b = ptr;
时,您正在将 ptr
的 值 复制到 b
。之后,ptr
和b
都指向同一个地址,但这两个指针是同一个值的两个独立的副本,每个副本放在内存中的不同位置。取 b
的地址自然会产生与 ptr
.
地址不同的东西
这是我正在尝试的:
int a,b;
int *ptr;
a = 123;
ptr = &a;
b = *ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("&ptr is %p\n",&ptr);
printf("&b is %p\n",&b);
结果:
&a is 0x7ffee01fc828
ptr points to 0x7ffee01fc828
&ptr is 0x7ffee01fc818
&b is 0x7ffee01fc820
我希望 &b 显示与 &a 相同的地址...但事实并非如此,所以我尝试了:
int a,*b;
int *ptr;
a = 123;
ptr = &a;
b = ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("&ptr is %p\n",&ptr);
printf("&b is %p\n",&b);
这仍然会导致 &b:
的意外内存地址&a is 0x7ffee1cbd828
ptr points to 0x7ffee1cbd828
&ptr is 0x7ffee1cbd818
&b is 0x7ffee1cbd820
谁能帮我理解为什么我无法获得与 &ptr 或 &a 匹配的相同地址的 &b?
谢谢!
现在 a
、b
和 ptr
是 3 个不同的变量(无论其类型如何)
所以他们的地址是不同的。通过 not 获取指针变量的 address,您将获得相同的值。
int a,*b;
int *ptr;
a = 123;
ptr = &a;
b = ptr;
printf("&a is %p\n",&a);
printf("ptr points to %p\n",ptr);
printf("b is %p\n",b);
I expected &b to show the same address as &a…
有这种期望意味着您对指针如何工作以及它们在 C 编程语言中的语义有什么错误的心理模型。关键的误解似乎发生在原始代码片段的这两行:
首先你有
b = *ptr;
这一行转换为 *"copy the contents of the memory at address ptr
into the variable b
." 变量 b
甚至从未接触过指针本身。您可以将它完美地重写为相同的效果
int tmp = *ptr;
b = tmp;
事实上,每个现代 C 编译器都会为这两种情况生成相同的代码。
你误会的第二行就是这一行
printf("&b is %p\n",&b);
特别是取变量b
地址的效果,即&b
的结果。 b
是一个完全独立的变量,有自己的地址。 无法更改此地址! 变量唯一可以更改的是它的值。
指针也是变量,是的,指针本身确实有一个地址。指针的值是它指向的地址。但是像每个变量一样,您不能更改存储变量的地址,并且当您将地址分配给指针时,您正在更改它的值。因此,当您在第二个代码片段中分配 b = ptr;
时,您正在将 ptr
的 值 复制到 b
。之后,ptr
和b
都指向同一个地址,但这两个指针是同一个值的两个独立的副本,每个副本放在内存中的不同位置。取 b
的地址自然会产生与 ptr
.