hello,

i have a simple question: how can i make 2 variables to have the same address. For example, if i write:

int a = 10;
int &b = a;

everything goes ok
"a" and "b" have the same value and the same address

but what ai need is:

int a = 10;
int b = 3;
...do some modification...
and then i want to make "b" to have the same address and the same value as "a"...

any idea?...pls

You cant have variables stored in the same memory address. You can point to a memory address and store the value in that memory address to a different memory address.

nope. you are wrong. you can have 2 variables with the same address:

int a = 10;
int &b = a;

but i know to do this only at declaration. What i need is to chance the address of b after a while:

......
int a = 10;
int b = 3;
...do some modification...
and then i want to make "b" to have the same address and the same value as "a"...
......

No YOU are wrong, that is not 2 variables at the same address, that is a variable and a reference to the same variable. A reference is not a variable.

You can not have 2 variables at the same address, the standard specifically mandates against this.

You can not change the address of an object once it has been assign by the compiler.


You might be able to achieve what you want by using pointers

int a, c;
int *b = &c;

a = 10;
*b = 3;

// then later

b = &a;

b is just refrence to a;
a++;
will reflect change in b ;
but that doesnt mean they are havin same address !!!
b is not a variable its just refrence !!


&b will always give address of a !!
becoz b is pointing to a;

int main(int argc, char** argv){
int a =10;
int &b = a;

cout <<"a = "<<&a<<"  "<<a<<endl; 
cout <<"b = "<<&b<<"  "<<b<<endl;

int c = a + b;  //use b like an usual variable

cout <<"c = "<<&c<<"  "<<c<<endl;

b = 3; // this will change also the value of a ... a = 3

cout <<"a = "<<&a<<"  "<<a<<endl; 
cout <<"b = "<<&b<<"  "<<b<<endl;

	return 0;
}

and the result:

a = 0012FF60 10
b = 0012FF60 10
c = 0012FF48 20
a = 0012FF60 3
b = 0012FF60 3

This does not mean that "b" has the same address as "a" ???

b is not actually AT address 0012ff60 it is at a different address, but the compiler treats it like it is at the same address. You might call it an "automatic" pointer, similar to if you pass a variable to a reference parameter in a function (instead of as an actual pointer).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.