pointers question

Started by
2 comments, last by iMalc 13 years, 3 months ago
Test::Test(int id, double *ptr)
{
id = ptr; // what does this do?

id = *ptr; // what does this statement do as well?

}


-thx im a bit confused on pointers and trying to understand this
Advertisement

Test::Test(int id, double *ptr)
{
id = ptr; // what does this do?

id = *ptr; // what does this statement do as well?

}


-thx im a bit confused on pointers and trying to understand this


id = ptr sets the id to be the memory address to which the pointer to ptr points towards. So its the address the computer uses internally
id = *ptr; the pointer will be dereferenced and will then get access to the contents in memory. So most likely the double value your interested in. Then it will most likely be a truncated double value since id is an int.

You may for safety consider using a reference, a reference gets rid of the need of dereferencing the variable while passing around memory addresses.

Test::Test(int id, double *ptr)
{
id = ptr; // what does this do?

id = *ptr; // what does this statement do as well?

}


-thx im a bit confused on pointers and trying to understand this


Well the first statement results in a compile error. Its not legal. You can't assign a 'double *' to an 'int'.

The second statement dereferences the pointer to retrieve the data that the pointer points to. If '*ptr' evaluates to 1.59377, then the value of 'id' would be 1, because your 'double' (ptr is of type double) would be cast to an 'int' and truncation would occur.

Don't get it? Check this out:
http://www.cplusplus...orial/pointers/

All those tutorials are pretty good. Good luck!

You may for safety consider using a reference, a reference gets rid of the need of dereferencing the variable while passing around memory addresses.
Not to mention that it also prevents you from accidentally making it point to reference something else, and relieves you of any burden of having to check for it being a NULL pointer.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement