Exploring Memory Addresses in C++

mdshamsfiroz
2 min readOct 22, 2024

--

Hey there, fellow coders! Today, we’re going to dive into a fun little C++ exercise that’ll help us understand how our programs manage memory. We’ll create a function that shows us where our variables live in the computer’s memory. Cool, right?

The Challenge

Our mission is to write a C++ function called memoryAddresses that does two simple things:

  1. It takes two variables of different types.
  2. It figures out and shows us where these variables are stored in memory.

The twist? We can’t use any fancy library functions to do this. We’re going old school!

Let’s Code It Out

Here’s how we can write this function:

void memoryAddresses(int& var1, double& var2) {
// Get address of first variable
unsigned long long addr1 = (unsigned long long)&var1;
std::cout << "Address of var1: " << addr1 << std::endl;
// Get address of second variable
unsigned long long addr2 = (unsigned long long)&var2;
std::cout << "Address of var2: " << addr2 << std::endl;
}

Now, let’s use this in our main program:

int main() {
int myInt = 42;
double myDouble = 3.14;
memoryAddresses(myInt, myDouble);
return 0;
}

When we run this, we’ll see something like:

Address of var1: 140732920751084
Address of var2: 140732920751072

Github Link:-https://github.com/mdshamsfiroz/Arth-4-Tasks/blob/main/C%2B%2B/Task3.cpp

What’s Going On Here?

Let’s break it down:

  1. We’re using the & operator to get the memory address of each variable.
  2. We’re casting these addresses to unsigned long long to make sure we can hold any address our computer might use.
  3. We’re printing these addresses as regular numbers.

The numbers you see are actually memory locations in your computer. Cool, huh?

Why This Matters

Understanding memory addresses is super important in C++. It helps us:

  • Understand how pointers work
  • Debug tricky memory issues
  • Optimize our code for better performance

Plus, it’s just plain fun to see where our variables live in the computer’s memory!

Wrapping Up

And there you have it! We’ve peeked under the hood of our C++ program and seen where our variables hang out in memory. Next time you’re debugging a tough problem, remember this little trick. It might just save your time and efforts.

So, whether you’re a tech enthusiast, a professional, or just someone who wants to learn more, I invite you to follow me on this journey. Subscribe to my blog and follow me on social media to stay in the loop and never miss a post.

Together, let’s explore the exciting world of technology and all it offers. I can’t wait to connect with you!”

Connect me on Social Media: https://linktr.ee/mdshamsfiroz

Happy coding! Happy learning!

--

--

mdshamsfiroz
mdshamsfiroz

Written by mdshamsfiroz

Trying to learn tool by putting heart inside to make something

No responses yet