我有一个简单的程序
int main()
{
int a = 1; // variable declaration
printf("a before: %d \n", a); // a is 1
int* b = &a; // pointer declaration - get the memory address of variable `a` with the `&` reference opeartor
*b = 2; // dereference to access data contained the memory block of variable `a` via the the `*` dereference operator
printf("a after : %d", a); // a becomes 2
return 0;
}我想知道哪种心理模型是正确的:
a指向存储数据int 1的内存地址100000f91。通过执行此赋值*b = 2,我们将内容/数据从int 1更改为int 2,但数据仍然位于原始内存地址,即int 1中。通过执行此赋值(
*b = 2 ),我们将变量a从内存地址100000f91指向的位置更改为其他地方,例如存储新数据int 2的100000f92如果我错了,请随时纠正我。无论心智模型是正确的,当我们引用一个函数传递a时,我想知道相同的心智模型是否仍然适用
void fn(int* b) {}发布于 2022-01-11 22:13:26
变量的地址在其生存期内从不更改。
这意味着直接更改变量的值:
a = 2;或间接:
b = &a;
*b = 2;不要改变它的地址。所以你的第一个心理模型是正确的。
此外,这一说法是不正确的:
假设变量a指向内存地址
a不是指针类型,所以它不指向地址。与所有变量一样,它有一个不变的地址。
发布于 2022-01-11 22:15:24
变量a不会在内存中移动。一旦定义了变量a的内存,就会立即分配它。
变量a没有指向任何地方。它被设计为存储int类型的对象。
是指针b存储变量a的地址。
int* b = &a;因此,取消引用指针,我们可以访问分配给变量a的内存,并可以更改该内存中存储的对象。
这里有一个演示程序,可以帮助您轻松理解。
#include <stdio.h>
int main( void )
{
int a = 1;
printf( "The address of the variable a is %p\n", ( void * )&a );
int *b = &a;
printf( "The address stored in the variable b is %p\n", ( void * )b );
*b = 2;
printf( "After the assignment the address of the variable a is %p\n", ( void * )&a );
}程序输出可能类似于
The address of the variable a is 006FF9D4
The address stored in the variable b is 006FF9D4
After the assignment the address of the variable a is 006FF9D4正如你在任务完成后所看到的
*b = 2;变量a的地址没有更改。它是存储在被更改的变量a占用的内存中的值。
您可以将变量视为指定的内存范围,用于存储用于声明该变量的指定类型的对象。
https://stackoverflow.com/questions/70674051
复制相似问题