简体   繁体   中英

Confused with references on pointers in C++

The task is to calculate the output of the following source code without a computer, which I would say is "123 234 678 678" because ref1 is a reference on the value of ptr and in the moment where the address of val2 is assigned to this pointer, then shouldn't ref1 as well refer to its value?

int main() {
    int* ptr = nullptr;
    int val1 = 123, val2 {234};
    ptr = &val1;
    int& ref1 = *ptr;
    int& ref2 = val2;

    std::cout << ref1 << " ";
    std::cout << ref2 << " ";
    *ptr = 456; //ref1 = 456
    ptr = &val2; //*ptr = 234, why isn't ref1 as well equal to 234?
    *ptr = 678; //*ptr = 678, why isn't ref1 as well equal to 678?

    std::cout << ref1 << " ";
    std::cout << ref2 << "\n";

    return EXIT_SUCCESS;

    //output: 123 234 456 678
}

After this declarations

int& ref1 = *ptr;
int& ref2 = val2;

ref1 refers to val1 and ref2 refers to val2 . After the declarations the references can not be changed to refer to other variables.

Pay attention to that the reference ref1 does not refer to the pointer ptr . It refers the variable val1 due to dereferencing the pointer that points to the variable val1 .

So these statements

std::cout << ref1 << " ";
std::cout << ref2 << " ";

will output

121 234

In this statement

*ptr = 456;

the value of the variable val1 is changed to 456 through using the pointer ptr .

After that the value of the pointer ptr was changed to store the address of the variable val2

ptr = &val2;

and the value of the variable val2 was changed to 678 through using the pointer

*ptr = 678;

So these statements

std::cout << ref1 << " ";
std::cout << ref2 << "\n";

now will output

456 678

That is they output values of the variables to which the references refer to.

In this program the same one pointer was used to change values of two different objects due to reassignment of the pointer with addresses of the objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM