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

爷,独闯天下 提交于 2020-01-12 02:50:52

问题


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!


回答1:


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

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



回答2:


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

int x = 42;

and (for example) the computer has stored x at address location 5, &x would be 5. Likewise you can store that address in a variable called a pointer:

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

Once you have a pointer you can dereference it 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.



回答3:


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 x and *y would yield 5



来源:https://stackoverflow.com/questions/2702156/what-is-the-difference-between-the-and-the-operators-in-c-programming

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!