The Mask
The Mask

Reputation: 17457

How do I get this address?

I have this:

  unsigned int y = (unsigned int)(int*)foo;

How do I get the address to where is stored in memory value which foo points?

Let's try to explain better, assume that thery are of int type:

int x = 10;
int *foo = &x;
unsigned int y = (unsigned int)(int*)foo;
int r = MAGIC(y); /* should be 10 */
x = 13; /* r still should be 10 */

y should hold x's adddress, it is, address of 10 integer.

r should copy the value at y location, it is, 10 integer.

so any change of x (as in x = 13) shouldn't change value r. This just an int.

The question is: How do I define MAGIC?

Upvotes: 0

Views: 120

Answers (3)

JackCColeman
JackCColeman

Reputation: 3807

Your code is trying to use y as a pointer when in fact it is defined to the C-compiler as an unsigned integer. Code that was written back in the "bad ol' days" would do stuff like your example.

Code should be more explicit and well defined in its intent, thus:

    #include <stdlib.h>
    main()

    {
    int x = 10;
    int *foo = &x;

    int *y = foo;

        #define MAGIC(A) *A
    int r = MAGIC(y); /* should be 10 */

    x = 13; /* r still should be 10 */

    printf("x=%d, r=%d", x, r);
        // printed (as expected) :: x=13, r=10

     }

These days there is NO reason to work around a C-compiler!!

If you are maintaining some old code that does stuff like your original example, then it is probably worth the effort to re-write it using today's programming style. Note, it can remain written in C, just well-formed C!

Upvotes: 1

David Elliman
David Elliman

Reputation: 1399

If y is to hold the address of x then it should be declared as:

unsigned int *y;

MAGIC should simply be the what is pointed to by operator.

int r = *y;

MAGIC is just the asterisk.

Upvotes: 0

Oswald
Oswald

Reputation: 31685

If what you want is possible, then

#define MAGIC(y) (*((int*)(y)))

will do it.

Upvotes: 3

Related Questions