2

I was wondering if I could capture a variables address that I could display by using

fprintf(stdout, "%p\n", (void*) &var); 

and actually place it into another variable, without displaying it.

(Into a String variable, not into it's actual address)

I have tested this with setbuf and everything but it still displays the String which I would not want.

I have tried looking everywhere but all I see is using either setbuf or some other means that doesn't fit what I am looking for.

1
  • 2
    So you want to place the pointer's address as a string into a char *? Have you tried sprintf(mystr, "%p", (void*) &var)? Here mystr would be a pointer to a character array. Commented Apr 30, 2015 at 18:42

4 Answers 4

4

You can capture a string representation of an address in the same way that you capture any output in a string - by using sprintf function:

char buf[17];
sprintf(buf, "%p", (void*) &var);

At this point buf contains a null-terminated string with a representation of var's address suitable for printing.

Of course if you wish to keep the string beyond the scope of buf you need to allocate another string dynamically, and strcpy your buf into it.

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

1 Comment

Yes, though probably minus the \n.
2

You can use something like this:

void* pointerToVar = &var;

fprintf(stdout, "%p\n", pointerToVar); 

Comments

0

I tried the first post and it worked also.

We also tried a modified version of this and it also works like this.

char a = 5; // Random number, literally has no importance

unsigned long long int b = (unsigned long long int) &a;

int num = abs(b);

1 Comment

abs() requires an int parameter, not a unsigned long long int parameter. using the suggested code causes the compiler to raise a warning. and the value is already unsigned, so why bother with abs()?
-1

pointer is really just an integer (address). You could do this:

float var;
int addr_of_var = (int)(&var);

depending on the platform, it might be long int, I think.

2 Comments

The won't work on most 64bit systems. Use intptr_t or uintptr_t instead of int or just void* for any pointer.
"pointer is really just an integer" this might be true for some implementations, but definitly not for all. For an example you might like to read here: en.wikipedia.org/wiki/Memory_segmentation (It's been not so long we used this... ;-))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.