A variable is normally used to store data in the main memory
A variable has 5 attributes
Value
Type
Name
Address
Scope
The address of a variable is usually in hexadecimal
0x00023AF0 for 32-bit computers
0x00006AF8072CBEFF for 64-bit computers
Pointer and its operations
Definition of Pointer
A pointer is a variable that stores the memory address of another variable
When a pointer stores the address of a variable, we say the pointer is pointing to the variable
A pointer, like a normal variable, has a type. The pointer type is determined by the type of the variable it points to
Basic Pointer Operators: & and *
int x = 2;int *xPtr = &x; // * used as pointer typecout << &x << endl; // 0x16d29b2f8cout << xPtr << endl; // 0x16d29b2f8cout << *xPtr << endl; // * used as dereference operator which prints 2
& address operator: get address of a variable
* is used in 2 ways
* in declaration: it indicates a pointer type
e.g. int *p is a pointer that points to an int variable
* in other statements: it is a dereference operator
Common Pointer Operations
p1 = &x; // Set a pointer p1 point to a variable xp2 = p1; // p2 and p1 now points to the same memory area*p2 = 10; // Update the value of the variable pointed by a pointerint x = *p2; // Retrieve the value of the variable pointed by a pointer
Common Errors
int x = 3;char c = 'a';char *ptr;ptr = &x; // error: ptr can only point to char, not intptr = c; // error: cannot assign a char to a pointer // A pointer can only store a memory addressptr = &c;
Pass by Pointer
Pass-by-Reference vs Pass-by-Pointer
void myFunc(int &num) { num = 3;}int main() { int x = 2; myFunc(x); cout << x; // 3 return 0;}