user3464330
user3464330

Reputation: 47

Can two pointers use the same address? (Code explanation)

int i1;
int i2;

int *ptr1;
int *ptr2;

i1 = 1;
i2 = 2;

ptr1 = &i1;
ptr2 = ptr1;

*ptr1 = 3;
i2 = *ptr2;

Can someone explain this code for me please? Specially line number eight, I think that it's assigning the address of pointer1 in pointer2, does that makes pointer2 point to the value 1?

Please someone help me. Thank you.

Upvotes: 1

Views: 303

Answers (5)

Luca Davanzo
Luca Davanzo

Reputation: 21520

Understanding pointer in C is the way.

Pointer basically is a variable whose value(R-value) is the address(L-value) of another variable.

Variable has a L-value (memory address where it is stored) and R-value (data value).

So

ptr2 = ptr1;

mean that you are assigning to the R-value of ptr2 the R-value of ptr1.
Ptr1's R-value contains i1's L-value, so:

cout << ptr2;  /* print i1's L-value (a memory address) */
cout << *ptr2; /* print 1, that is i1's R-value */

Upvotes: 0

William Pursell
William Pursell

Reputation: 212228

ptr2 = ptr1 assigns the value of ptr1 (which is the address of i1) to ptr2. This makes ptr2 point to the same thing that ptr1 points to, namely, the variable i1. The value in the location pointed to by ptr2 is indeed, 1, but it certainly seems odd to say that ptr2 points to the value 1. The value of ptr2 is a memory location, and that location currently contain a collection of bits which (when interpreted as an int) represent the value 1.

Upvotes: 1

Haris
Haris

Reputation: 12270

int i1; //initialize 2 integers
int i2;

int *ptr1; //initialize 2 pointer to integers
int *ptr2;

i1 = 1; //storing values into the integer variables
i2 = 2;

ptr1 = &i1; //pointer ptr1 pointing to the address of the integer variable i1
ptr2 = ptr1; //pointer ptr2 pointing to the address pointed by ptr1 (perfectly ok)

*ptr1 = 3; //value at the address pointed by ptr1 changed to 3 (which changes the value at the address pointed by ptr2 also
i2 = *ptr2; //value at the address pointed by the ptr2 stored in integer variable i2

Upvotes: 1

Yann Vernier
Yann Vernier

Reputation: 15877

Yes, multiple pointers can point to the same location, a situation known as aliasing. And while the line you mention does make ptr2 point to the value 1, more importantly it points to the storage of i1, as does ptr1. So at that point you have three different names to access i1 by: *ptr1, *ptr2 and i1 itself. As such the last two lines do have a sequential dependency, and the program ends up with 3 in both i1 and i2.

Upvotes: 1

Voidpaw
Voidpaw

Reputation: 920

What you are doing is writing the value of ptr1 in the address of ptr2. To visualise: the you have an arrow in ptr1 that says "if you need value1, you can get it right there". After the copy, ptr2 now also has an arrow that says "if you need value1, you can get it right there". So you were indeed correct in assuming that ptr2 points to the value 1.

Upvotes: 0

Related Questions