Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same address of two variables?

Tags:

c

How can I declare two different variables (say x and y) that have the same address?

   printf("%p\n",&x);  /*will be same */
   printf("%p\n",&y);

If possible without union?

like image 747
Farseer Avatar asked Mar 23 '13 18:03

Farseer


2 Answers

The precise thing you asked for cannot be done using only the standard facilities of the language, but some compilers have extensions that permit it. For instance, with GCC this might do what you want (documentation here).

#define ASMNAME(x) ASMNAME_(__USER_LABEL_PREFIX__, #x)
#define ASMNAME_(x,y) ASMNAME__(x, y)
#define ASMNAME__(x,y) __asm__(#x y)
int x;
extern int y ASMNAME(x);

int main(void)
{
    return !(&x == &y); /* will exit successfully */
}

Note well what effect this has, though: in the object file, there is only one variable, and its name is x. y has only been declared as another name for it in the source code. This may or may not be good enough depending on what you're trying to do.

Note also that the two variables are treated as distinct for optimization purposes. For instance:

#define ASMNAME(x) ASMNAME_(__USER_LABEL_PREFIX__, #x)
#define ASMNAME_(x,y) ASMNAME__(x, y)
#define ASMNAME__(x,y) __asm__(#x y)
int x;
extern int y ASMNAME(x);

#include <stdio.h>

int main(void)
{
   int a, b;
   x = 1;
   a = x;
   y = 2;
   b = x;
   printf("a=%d b=%d x=%d y=%d\n", a, b, x, y); 
   return 0;
}

may well print

a=1 b=1 x=1 y=2

because the store to y is not considered to affect the value of x.

like image 179
zwol Avatar answered Nov 22 '22 15:11

zwol


What @Mysticial saying is correct. Union elements share memory space. and two variables in union have same start address. following is my example program and its output may help you to understand.

#include<stdio.h>
union u{
 int x;
 int y;
};
union u a;
int main(){
    printf("\n %p %p\n",&a.x, &a.y);
    return 1;
}

Output:

~$ ./a.out 

0x601030 0x601030

Additionally, as @Alon idea, in C++ you have one more kind of variable called reference variable is alias of other variable. you can create like: (you question is taged C, In C you don't have reference variables) see below:

int a = 10;
int &b = a; 

+----+----+
|   10    |  <--- a = b
+----+----+  
  2002         

if you print &a and &b then you will get 2002 same.

like image 36
Grijesh Chauhan Avatar answered Nov 22 '22 17:11

Grijesh Chauhan