Home > Mobile >  How to convert variable's address to string variable in C?
How to convert variable's address to string variable in C?

Time:09-14

How to store address string to a char *variable or char array?

#include <stdio.h>

int main()
{
    int number = 1200;
    printf("Address = %p\n", &number);
    // char address[30];

    return 0;
}

CodePudding user response:

Here is one way of doing it:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int number = 1200;
    size_t n = 0;
    int n2;
    char *s = NULL;
retry:
    n2 = snprintf(s, n, "Address = %p", &number);
    if(n2 < 0) {
        printf("snprintf failed\n");
        return 1;
    }
    if(!n) {
        n = n2   1;
        s = malloc(n);
        if(!s) {
            printf("malloc failed\n");
            return 1;
        }
        goto retry;
    }
    printf("%s\n", s);
    free(s);
    return 0;
}

and for me it prints:

Address = 0x7ffea89d5e6c

CodePudding user response:

To convert variable's address to string, use snprintf() with "%p" and cast the object address to void *.

Cast conforms to the C spec.

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

The only tricky bits remaining are determining a reasonable size and managing the buffer.


I like a single call to snprintf() with a generous buffer scaled to a reasonable worst case size.

#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#define PTR_FMT "Address = %p\n"
// How about allowing a charter per pointer bit and a "0x"` to handle %p "implementation-defined manner".
#define PERCENT_P_FMT_SIZE (sizeof(void *) * CHAR_BIT   3)

int main(void) {
    int number = 1200;

    char buf[sizeof PTR_FMT   PERCENT_P_FMT_SIZE];
    int len = snprintf(buf, sizeof buf, PTR_FMT, (void *) &number);
    assert(len > 0 && (unsigned) len < sizeof buf); 
    fputs(buf, stdout);
}

CodePudding user response:

Based on your sample (using a local character buffer)...

#include <stdio.h>

int main() {
    int number = 1200;

    printf( "Address = %p\n", &number );

    char buf[30]; // generous enough?
    sprintf( buf, "%p", &number );

    printf( "Address = %s\n", buf );

    return 0;
}
  • Related