1

Here is a sample code. I want to get address of int K that is in Volume() and also Length. How can i do that?

 #include <iostream> using namespace std; class Box { public: Box(double l = 2.0) { length = l; } double Volume() { cout<<"Done"<<endl; int k=300; } public: double length; }; int main() { Box Box1(5); Box *ptrBox; ptrBox = &Box1; cout << "Volume of Box1: " << ptrBox->Volume() << endl; return 0; } 

How can i get the address of a variable in a class and a variable in a method in that class ?

4
  • 3
    int k is not a class member variable but a local variable (of function Box::Volume()). To get its address is possible but very probably the prerequisite for Undefined Behavior. However, to access Box::length is quite easy (as you made it public): Box1.length would do the job as well as ptrBox->length. (Didn't you learn this in your C++ book?) And, btw. your function Box::Volume() has a non-void return type but you didn't return anything. (That's Undefined Behavior as well.) Maybe, you intended to return k; but forgot to write it down? Commented Mar 16, 2021 at 14:28
  • The undefined behavior is because i picked an example code and stripped it to fit my question. I was able to get 'Box1.length' address but i cant find a way to get 'int k' 's address. Commented Mar 16, 2021 at 14:40
  • int k is a variable with automatic storage. That means its location is chosen every time Volume() is called. And it no longer exists when Volume() returns. At any moment, there may be many instances of that k, or there may be none. Commented Mar 16, 2021 at 14:43
  • I could show you how to get int ks address but I wouldn't do you a favor with this. k is a local variable in Box::Volume() and its life-time (aka. existence) just ends when the execution returns from the call of ptrBox->Volume(). Returning the address of k would end up in a dangling pointer which points to nothing which may be accessed. (Hence, I mentioned Undefined Behavior as this is how it is called in C++ if you do something which you can do but you shouldn't do.) Commented Mar 16, 2021 at 14:43

1 Answer 1

1

To get the address of any variable:

int i; int * ptr = &i; 

You already kind of do this. Well, you can also do:

double * dPtr = &Box1.volume; 

It's not any different. It is, however, a really bad idea. You're also successfully getting the address of a variable in the method, but understand that the local variable is going to go away, and it's a really, really bad idea to use it after the method ends.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.