Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are `x = &v` and `*x = v` equivalent?

Tags:

c++

pointers

int * x;
int v = 7;

Given this code, what is the difference between 1. x = &v , and 2. *x = v ? I understand that in both cases, *x contains 7 but does x contain memory location of v in both cases? If not, what does x contain in cases 1 and 2, and is this the only significant difference between the two?

like image 681
Arjun Viswanathan Avatar asked May 21 '20 13:05

Arjun Viswanathan


People also ask

Does Netflix Have we X?

Watch We Are X | Netflix.

Why did X Japan disband?

On September 22, 1997, Yoshiki, Hide, Pata and Heath held a press conference where they announced that X Japan would disband. Vocalist Toshi decided to leave the band, claiming that the glamorous, success-oriented life of a rock star failed to satisfy him emotionally, as opposed to a simpler life and career.


1 Answers

Given the statement:

int v = 7; 

v has some location in memory. Doing:

x = &v;

will "point" x to the memory location of v, and indeed *x will have the value 7.

However, in this statement:

*x = v;

you are storing the value of v at the address pointed at by x. But x is not pointing at a valid memory address, and so this statement invokes undefined behavior.

So to answer your question, no, the 2 statements are not equivalent.

like image 159
cigien Avatar answered Sep 19 '22 10:09

cigien