unj2
unj2

Reputation: 53551

How do I print the value of a parameter when the type is not known in C?

How do I know what a particular address pointed by my pointer contains? I want to print the content in this address location? What should I add as a placeholder?

Upvotes: 2

Views: 195

Answers (5)

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74450

Any other pointer type can be cast to a void pointer to print its address:

char c='A';
char *pc=&c;

printf("%p",(void *) pc);

Now, if you want the character at this address:

char c='A';
char *pc=&c;

printf("%c",*pc);

Upvotes: 2

Jengerer
Jengerer

Reputation: 1163

Another way you could do it is to refer to your data as a void* and then refer to that as an unsigned char*, and print everything out as hexadecimal bytes. I found it was really useful when having to deal with contiguous bytes where their use was not yet known.

However, this method requires that you have a way of knowing how long your data is, as there's no way to call sizeof on data of arbitrary type.

#include <stdio.h>

int main() {
    char name[16] = "hello there";
    void* voidBuffer = name;

    unsigned char* buffer = voidBuffer;
    int i;
    for (i=0; i<16; i++) {
        printf("%x ", (unsigned int)buffer[i]);
    }

    return 0;
}

This would output 68 65 6c 6c 6f 20 74 68 65 72 65 0 0 0 0 0.

Upvotes: 2

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133112

If your question is - how can you deduce the type of the object stored at a given location denoted by void*, then you can't. If your question is how can I know the value of the byte my void* points to, then it is

unsigned char valueAtAddressP = *((unsigned char*)p);

Upvotes: 3

rkg
rkg

Reputation: 5719

You can do it in multiple ways

int x = 5;
int *ptrX = 6;
printf("The pointer of x is: %d", &x);
printf("The ptrX is: %d", ptrX);

Both of the above approaches give you the address value.

Upvotes: 1

Donotalo
Donotalo

Reputation: 13035

There is no way to detect that in C. Your application should treat the data pointed to by the pointer to a specific type - depends on your needs.

void treat_as_char(const void* ptr)
{
    const char *p = ptr;
    printf("Data: %s\n", p);
}

void treat_as_int(const void* ptr)
{
    const int *p = ptr;
    printf("Data (int): %d\n", p);
}

You need some custom structure to allow various type for a specific pointer:

typedef struct _Variant
{
    enum {INT, CHAR, DOUBLE} type;
    void *ptr;
} Variant;

Upvotes: 3

Related Questions