I have to reproduce the printf function in C. I am getting problem with printing addresses (%p). So i have an address of variable and I need to return it as an array of char. Is it even possible?
char *ptrToString(void * x)
{
char *t = (char *)x;
printf("Here: %s\n",t);
return "abc";
}
char *getPtr(unsigned long long x)
{
return ptrToString(&x);
}
CodePudding user response:
Pointers are numeric types, so in printf
-like functions use either %p
(preferred), %x
or %d
to print them.
Your ptrToString could look something like this:
#include <stdio.h>
#include <stdlib.h>
const char *x = "test";
char *ptrToString(void *x) {
char *s = malloc(sizeof(void*) * sizeof(char));
sprintf(s, "%p", x);
return s;
}
int main() {
char *a = ptrToString( (void*) x);
if (!a)
return 1;
printf("%s\n", a);
free(a);
return 0;
}
CodePudding user response:
First a small note:
char *getPtr(unsigned long long x)
{
return ptrToString(&x);
}
int main()
{
long long someLong = 1;
char *ptr = getPtr(someLong);
return 0;
}
Here ptrToString will return the address of variable x on the stack rather than the address of variable someLong because the value of the variable will get copied on the stack as a totally separate entity.
As for the answer itself, an address is actually just a number representing byte offsets in memory. To convert this number to a string, you need a variant integer to ascii-like function where you convert to base 16 instead of base 10.
I assume sprintf
is not an option, so you'll have to implement your own variant of a decimal to hex string converter. Cast any address to a wide unsigned integer type and convert that number to hex.