Help with C++ pointers (not completely, just a simple question)
6 replies, posted
I know this
int x;
int *p;
p = &x;
would make p == memory address of x, and *p == x. but what if i did this
int x;
int *p;
*p = &x;
if p pointed to int now what does it point to...? and what will this turn out to be? (no access to compiler, sorry :P)
If p was an initialized pointer to another pointer, that would be valid. It's a pointer to an int, so it tries putting the address of x into an int. This will work in C without a cast, but it won't work in C++ without a cast.
Undefined behaviour will occur when you dereference that uninitialized pointer though.
edit:
And to clarify, you're not actually changing the pointer, only the value it points to, so the pointer remains the same.
This helped me, thank you for taking the time to explain. I was hoping I wasn't going to get a short answer.
[QUOTE=jA_cOp;19617892]And to clarify, you're not actually changing the pointer, only the value it points to, so the pointer remains the same.[/QUOTE]
Curious,
int i = 10;
char j = 'j';
int* p;
p = &i;
&p = &j;
?
[QUOTE=Eleventeen;19621257]
&p = &j;[/QUOTE]
Try with valid C++ next time.
[QUOTE=Eleventeen;19621257]Curious,
int i = 10;
char j = 'j';
int* p;
p = &i;
[B]&p = &j;[/B]
?[/QUOTE]
What the hell is that supposed to do? If anything it would overwrite j, but it wouldn't because you can't just change the address of a variable willy nilly in C++, not that there is any reason anyone would ever want to.
[QUOTE=Eleventeen;19621257]Curious,[/QUOTE]
Were you curious if it would compile? Because it doesn't, for good reason.
Sorry, you need to Log In to post a reply to this thread.