Pointers and references are just ways of accessing data that is stored in memory. The basics of a pointer (*) are that is it will either store a NULL value or a value of a memory location where the actual data is. The reference (&) is the actual memory location address of a variable. I did do a function pointer tutorial (cpp-tutorials/tutorial-function-pointers-t101998.html) and this a follow on with what a pointer is.
Standard variable - memory layout
Lets say that at memory location 0x004 there was a value of 15. Well this memory location 0x004 could be called a integer value with a name of intValue, code example
int intValue = 15;
With the memory layout of
Memory location : Value 0x004 --------- : 15
Pointer assignment and value
A pointer to that variable at 0x004 (intValue) will have another memory location lets say at 0x010 so a code example would be
int *intPointer= NULL;
best practice to set to NULL, and if you want to assign the pointer to the intValue you will need to give the pointers memory location value the address of the intValue memory location as
intPointer = &intValue;
and now the memory example for 0x010 (the intPointer) would be
Memory location : Value 0x010 --------- : 0x004
It is the value of the actual memory location and not the value of 15, since that the value of intValue. To actually get the value you need to dereference the pointer with the * as below
cout << "pointer value = " << intPointer << " the value = " << *intPointer << endl;
That will output
pointer value = 0x004 the value = 15.
A pointer is a easy concept and also easy to mess up since you are playing with memory locations, but allot of fun at the same time.
I am going to do a tutorial on function parameters with pointers and references to memory locations and what is the reason for them.
I do really like to have any feedback regarding any tutorial/post, just reply or PM me.. glad to help, better to share knowledge.
This page was published on