-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointer.cpp
More file actions
62 lines (46 loc) · 2.49 KB
/
Copy pathpointer.cpp
File metadata and controls
62 lines (46 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
using namespace std;
int main() {
// ===================================================
// 1. CREATING POINTERS
// ===================================================
// A pointer is a variable that STORES THE MEMORY ADDRESS of another variable as its value.
// The pointer type must match the data type of the variable it points to.
string food = "Pizza";
// Pointer declaration using `*` and assigning memory address using `&`
string* ptr = &food; // Preferred way
/* Other valid syntax options for pointer declaration:
string *ptr = &food;
string * ptr = &food;
*/
cout << "=== 1. CREATING POINTERS ===" << endl;
cout << "Value of food : " << food << endl; // Output: Pizza
cout << "Memory addr (&food) : " << &food << endl; // Output: 0x...
cout << "Pointer value (ptr) : " << ptr << endl; // Output: 0x... (Same as &food)
// ===================================================
// 2. DEREFERENCING OPERATOR (*)
// ===================================================
// Using `*ptr` OUTSIDE of declaration is called the DEREFERENCE OPERATOR.
// Purpose: Gets the ACTUAL VALUE stored at the memory address held by the pointer.
cout << "\n=== 2. DEREFERENCING POINTER ===" << endl;
cout << "Address via ptr : " << ptr << endl; // Displays Memory Address
cout << "Value via *ptr : " << *ptr << endl; // Dereference -> Displays "Pizza"
// ===================================================
// 3. MODIFYING POINTER VALUE
// ===================================================
// Changing `*ptr` will modify the original variable's value (`food`) in memory.
cout << "\n=== 3. MODIFYING POINTER VALUE ===" << endl;
*ptr = "Hamburger"; // Modifies the value at memory location via pointer
cout << "New value via *ptr : " << *ptr << endl; // Output: Hamburger
cout << "New value of food : " << food << endl; // Output: Hamburger
// ===================================================
// KEY TAKEAWAYS & ASTERISK (*) RULES:
// ===================================================
/*
1. Asterisk `*` during DECLARATION (string* ptr) -> Creates a pointer variable.
2. Asterisk `*` during EXECUTION (*ptr) -> Dereference operator (Accesses/modifies the value).
3. Ampersand `&` -> Address-of operator (Retrieves memory address).
*/
return 0;
}