What is a pointer?
A pointer is commonly known as a reference to a location in memory. You can use it to locate a section of memory that you forgot the variable too or you can use it to exchange data between two locations in memory.
How do we declare a pointer value?
To declare a pointer value all one must do is place an asterisk between the data type and the identifier of a variable; like so.
int a = 5; int* pointerA = &a; printf("value of a: %d n", a); printf("value OF pointerA: %d n", pointerA);
Woa! Hold up, what is that & sign there for? The & sign is specified as an Address Operator which goes and gets the address in memory of integer a and returns it to the pointerA variable. The result of this program if you printed out what a and pointerA equals on my machine it will come up with:
That was cool. Now you know how to create a pointer, and how to assign an address to it.
Tip: If you are assigning an pointer to an array you do not need the asterisk because the array’s identifier already points to the address of the array.
How do I get a value from a pointer? Simple just place an asterisk in front of the identifier you are trying to get. You can read this as “The Value of” such as in the context below… Just append the line of code underneath to your file in the scope of main.
printf("value at pointerA: %d n", *pointerA);
Me reading the above line out loud:
“Print the value at pointer A to the console.” – Taylor Brazelton
Now you realize the point of pointers in C and C++ hopefully you aren’t summoned upon to use these skills but every now and then someone is. Enjoy the tutorial and use it to your benefit.