kelvinwong
kelvinwong

Reputation: 113

How to convert variable's address to string variable in C?

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;
}

Upvotes: 1

Views: 1141

Answers (3)

user9706
user9706

Reputation:

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;
}

Here's a goto-less version:

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

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

and for me it prints:

Address = 0x7ffea89d5e6c

Upvotes: 3

chux
chux

Reputation: 153348

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);
}

Upvotes: 4

Fe2O3
Fe2O3

Reputation: 8344

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;
}

Upvotes: 2

Related Questions