CodeBeauty
POINTERS introduction
#include <iostream> using namespace std; int main(){ /* int n = 5; cout << n << endl; output: 5 */
// is for a comment line and /**/ is for multiple line comments //I make it like this so you can paste it immediately into a compiler //variable - &address - *pointers. //START //just like variable, a pointer is a container as well, storing an address (a memory location) //n is a variable meaning that it is a container storing certain value //because it's a container, it has it's address inside the memory, a physical location //in order to check the location / which address :
/* int n = 5; cout << &n << endl; output: 006FFD64 */
//because it's not always fun to remember long address numbers, so we give them names - variables. we create a pointer to name an address and easily access it.
//POINTERS //how to create a pointer holding address of our n variable:
int n = 5; cout << &n << endl;int* ptr = &n; cout << ptr <<endl; //in order to indicate that you're creating a pointer, use * star (int*) //then give it a random name (ptr) //assign it (to ptr) the address of our n variable which is = &n (= assign)(& address)(n variable) cout << *ptr << endl; // a star * before the pointer's name will only reference the pointer and then find the VALUE of the ADDRESS //which is our original variable n //basically we're asking for the value 5, not the address 006FFD64 //CHANGE THE VALUE (5) stored in the pointer ptr address: *ptr = 10 ; //a star * means access the memory location and (=)assign a NEW (10) value //let's check if it's now 10 instead of 5 cout << *ptr <<endl; cout << n ; //both *ptr and n now show 10
//NOTES //pointer has to be of the SAME TYPE as the variable it is pointing to //int pointer to int variable, not int to float //char pointer to char variable, bool pointer to a bool variable, etc //you can't assign a value to a pointer, it has to point to an address //first create a (example) variable to store that variable's & address to the pointer //pointers are problem solvers and not the casual way it's used in these examples system("pause>0"); return 0; }
















