我只是确保我正确理解这个概念.使用*运算符,我创建一个新变量,在内存中分配一个位置.为了不必要地复制变量及其值,&运算符用于将值传递给方法等,它实际上指向变量的原始实例,而不是制作新副本......是吗?这显然是一种浅薄的理解,但我只是想确保我不会让他们混淆.谢谢!
Ste*_*sop 40
不完全的.*使用*运算符会出现在类型名称(用于定义变量)中的混乱.
int main() {
int i; // i is an int
int *p; // this is a * in a type-name. It means p is a pointer-to-int
p = &i; // use & operator to get a pointer to i, assign that to p.
*p = 3; // use * operator to "dereference" p, meaning 3 is assigned to i.
}
Run Code Online (Sandbox Code Playgroud)
fbr*_*eto 12
一个用于&查找变量的地址.所以如果你有:
int x = 42;
Run Code Online (Sandbox Code Playgroud)
和(例如)计算机存储x在地址位置5,&x将是5.同样,您可以将该地址存储在名为指针的变量中:
int* pointer_to_x = &x; // pointer_to_x has value 5
Run Code Online (Sandbox Code Playgroud)
一旦有了指针,就可以使用运算符取消引用它*,将其转换回它指向的类型:
int y = *pointer_to_x; // y is assigned the value found at address "pointer_to_x"
// which is the address of x. x has value 42, so y will be 42.
Run Code Online (Sandbox Code Playgroud)
当一个变量与 * 运算符配对时,该变量保存一个内存地址。
当它与 & 运算符配对时,它返回保存变量的地址。
如果你有
int x = 5; //5 is located in memory at, for example, 0xbffff804
int *y = &x; //&x is the same thing as 0xbffff804, so y now points to that address
Run Code Online (Sandbox Code Playgroud)
双方x并*y会产生5