Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c++ - Are `x = &v` and `*x = v` equivalent?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...