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 addre开发者_高级运维ss location? What should I add as a placeholder?
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;
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);
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
.
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);
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.
精彩评论