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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2702156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:16:32  来源:igfitidea点击:

What is the difference between the * and the & operators in c programming?

coperators

提问by Wesley

I am just making sure I understand this concept correctly. With the * operator, I make a new variable, which is allocated a place in memory. So as to not unnecessarily duplicate variables and their values, the & operator is used in passing values to methods and such and it actually points to the original instance of the variable, as opposed to making new copies...Is that right? It is obviously a shallow understanding, but I just want to make sure I am not getting them mixed up. Thanks!

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

回答by Steve Jessop

Not quite. You're confusing a *appearing in a type-name (used to define a variable), with the *operator.

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

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

回答by fbrereto

One uses &to find the address of a variable. So if you have:

一种用于&查找变量的地址。所以如果你有:

int x = 42;

and (for example) the computer has stored xat address location 5, &xwould be 5. Likewise you can storethat address in a variable called a pointer:

并且(例如)计算机已存储x在地址 location 5&x将是5。同样,您可以将该地址存储在称为指针的变量中:

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

Once you have a pointer you can dereferenceit using the *operator to convert it back into the type to which it points:

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

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.

回答by SteveStifler

When a variable is paired with the * operator, that variable holds a memory address.

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

When it is paired with the & operator, it returns the address at which the variable is held.

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

If you had

如果你有

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

both xand *ywould yield 5

双方x*y会产生5