Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the address as a char string in c?

Tags:

c

say I have the following:

#include <stdio.h>
#include <string.h>
int main() {
    char c = 'c';
    char addr[50];
    strcpy(addr, &c);

    printf("%p\n", &c);
    printf("%s", addr);

    printf("\n");
    return 0;
}

The above would print

0x7ffc241780af
c@@ //some gibberish

for the second line of the output, I am intending to output the char array so that it prints same as the first line. I am wishing to have memory address as a string so that I can manipulate with it, but how exactly do I get the memory address as a char string?

like image 335
please rekt me Avatar asked Nov 20 '25 11:11

please rekt me


2 Answers

Try this instead:

sprintf(addr, "%p", &c);
printf("%s\n", addr);
like image 84
dxiv Avatar answered Nov 23 '25 00:11

dxiv


The sprintf function is used to "print" to a string. So instead of

strcpy(addr, &c);

printf("%p\n", &c);
printf("%s", addr);

printf("\n");

try

sprintf( addr, "%p", (void *)&c );
printf( "%p\n", (void *)&c );
printf( "%s\n", addr );
like image 22
user3386109 Avatar answered Nov 23 '25 01:11

user3386109