Search code examples
c++pointers

confused about pointers


I just started learning c++ (I'm more of a java developer right now) and am having some confusion with using pointers... for example, the following code works

int main() {
    int x = 5;
    int * y;
    y = &x; //note this line of code
    *y = 10;
}

whereas this code does not work

int main() {
     int x = 5;
     int * y;
     y = x;
     *y = 10;
}

Can someone explain to me why getting the value "location" using y = &x works but as soon as I replace it with y = x it causes an error. If anyone knows of a good explanation on pointers please share the link :)

Thank you!


Solution

  • Let's see how this works with pointers.

    int x = 5;
    

    You're assigning the value 5 to x which is an int.

    int *y;
    

    You're declaring a pointer to an int.

    y = &x;
    

    Now, the address stored in y is the same as the address of x.

    But, if you do this : y = x, you're assigning an integer (5 in that case) to a variable that holds addresses of integers.

    Finally, you have to remember that :

    • & is the address-of operator, and can be read as "address of"
    • * is the indirection operator, and can be read as "value pointed to by"

    Tutorial about pointers