Cpp pointers & references
Pointers refer to the memory address a value is stored in. Passing a pointer as an argument, rather than the actual variable is generally a MUCH cheaper operation than copying the entire value into a new memory block.
Pointers
Using Pointers
int number_22 = 22; // the number 22 is assigned the memory cell #1076 cout << &number_22; // prints the POINTER, the memory-address of the variable cout << *1076; // prints 22. '*' indicates the value is a memory-addressstruct User{ string name; int age; }; User will; // create empty user `will` int * ptr_will = &will // create pointer to `will`s memory addr ptr_will->name = "Will Pittman"; // set attr using a pointer *will.age = 200; // set attr using a pointer (also valid)Creating Pointers
int * myvariable; // creates a pointer of type 'int' string * myvariable; // creates a pointer of type 'string'Nesting Pointers
It is possible to make pointers point to other pointers. When initializing a variable to store the pointer, you require one
*
per level away from the actual pointer.int * mystr; // a pointer, mystr int ** mystr; // a pointer, referencing a pointer int *** mystr; // a pointer, referencing a pointer, referencing a pointerArithmetic
See pointer arithmetics on http://www.cplusplus.com/doc/tutorial/pointers/, it is explaned very well.
Pointers can be added to or subtracted from. Pointer addition adds in units in the size of the pointer. Say we had a float which occupied 3bits. Adding 1 to it would add 3. Adding 1 a second time would add 6, etc.
References
Pointers and references are very similar. The difference is
- a pointer must be dereferenced in order to be used. (it points to the memory addr)
- a reference is a copy of the variable. It does not need to be dereferenced to be used (it points to the value, without using extra space)
General Use
int i = 3; int * pointer = &i; // &i refers to the address, (the pointer is made to refer to i's address) int &reference = i; // 'reference' can now be used interchangeably with i (without using more memory)As Arguments
In order to mark an argument as a reference, you use a suffix of
&
after the type.void my_func ( int& var_name ){ cout << var_name;; }