c编程中的*和&运算​​符有什么区别?

我只是确保我正确理解这个概念。 使用*运算符,我创建一个新变量,在内存中分配一个位置。 为了不必要地复制变量及其值,&运算符用于将值传递给方法等,它实际上指向变量的原始实例,而不是制作新副本……是吗? 这显然是一种浅薄的理解,但我只是想确保我没有让他们混淆。 谢谢!

不完全的。 您使用*运算符混淆了出现在类型名称(用于定义变量)中的*

 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. } 

一个使用&来查找变量的地址。 所以如果你有:

 int x = 42; 

和(例如)计算机已将x存储在地址位置5&x将为5 。 同样,您可以将该地址存储在名为指针的变量中:

 int* pointer_to_x = &x; // pointer_to_x has value 5 

一旦有了指针,就可以使用*运算符取消引用它,将其转换回它所指向的类型:

 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. 

当变量与*运算符配对时,该变量保存内存地址。

当它与&运算符配对时,它返回保存变量的地址。

如果你有

 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 

x*y都会产生5