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

44,026

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

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

Solution 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

Share:
44,026
Wesley
Author by

Wesley

Updated on July 09, 2022

Comments

  • Wesley
    Wesley almost 2 years

    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!

  • mfaani
    mfaani about 3 years
    How about these: *i or &p do they have any meaning?