C++ Memory Address

🧠 C++ Memory Address

In C++, every variable is stored at a specific memory location.
The memory address tells you where that variable is stored in RAM.


πŸ”Ή 1. Address-of Operator (&)

The & operator is used to get the memory address of a variable.

Example:

int x = 10;
cout << &x;

Output:

0x61ff08 // (example address, varies each run)

πŸ”Ή 2. Memory Address with Different Data Types

int a = 5;
float b = 3.5;
char c = 'A';

cout << &a << endl;
cout << &b << endl;
cout << &c << endl;

➑ Each variable has a different memory address.


πŸ”Ή 3. Store Memory Address in a Pointer

A pointer is a variable that stores a memory address.

int x = 10;
int *ptr = &x;

cout << ptr; // address of x
cout << *ptr; // value of x


πŸ”Ή 4. Dereferencing (* Operator)

  • ptr β†’ address

  • *ptr β†’ value at that address

int x = 20;
int *p = &x;

cout << *p; // 20


πŸ”Ή 5. Change Value Using Memory Address

int x = 5;
int *p = &x;

*p = 15;

cout << x; // 15

➑ Value changed through memory address.


πŸ”Ή 6. Memory Address of Array Elements

int arr[3] = {10, 20, 30};

cout << &arr[0] << endl;
cout << &arr[1] << endl;
cout << &arr[2] << endl;

➑ Addresses are contiguous (next to each other).


πŸ”Ή 7. Address of Reference Variable

int x = 10;
int &ref = x;

cout << &x << endl;
cout << &ref << endl;

βœ” Both addresses are the same.


πŸ”Ή 8. Why Memory Address Is Important

  • Used in pointers

  • Required for dynamic memory allocation

  • Improves performance (pass by reference)

  • Essential for low-level programming


❌ Common Mistakes

int *p;
cout << *p; // ❌ uninitialized pointer (dangerous)

βœ” Correct:

int x = 10;
int *p = &x;

πŸ” Memory Address vs Value

TermMeaning
ValueActual data (e.g., 10)
AddressLocation in memory
&xAddress of x
*pValue at address

πŸ“Œ Summary

  • Every variable has a memory address

  • Use & to get the address

  • Pointers store memory addresses

  • References share the same address

  • Fundamental for understanding pointers & memory

You may also like...