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

前端 未结 3 1276
忘了有多久
忘了有多久 2020-12-29 05:48

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 dupli

相关标签:
3条回答
  • 2020-12-29 06:15

    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.
    
    0 讨论(0)
  • 2020-12-29 06:18

    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

    0 讨论(0)
  • 2020-12-29 06:26

    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.
    }
    
    0 讨论(0)
提交回复
热议问题