Hi All,
I have a void* that is a pointer to either a char* or an int.
How do I determine which type the pointer is pointing to?
Thanks for your help,
rotis23
Printable View
Hi All,
I have a void* that is a pointer to either a char* or an int.
How do I determine which type the pointer is pointing to?
Thanks for your help,
rotis23
You don't
You can't directly from the pointer. You have to use some form of a trick.
Usually, a second parameter is passed to a function receiving type void * that specifies the type. Something like:
Another option would be to embed the type somewhere in the pointer like at the head of it.Code:void func(void *ptr, int type)
{
if(type == 1)
{
// do char * stuff
}
else
{
// do int stuff
}
}
Code:void func(void *ptr)
{
int type = *(int *)ptr;
((int *)ptr)++;
if(type == 1)
// etc., same as code above.
}
You can use a structure/union to pass around multiple types neatly:
For a mega sample see the Windows VARIANT type.Code:enum var_type { TYPE_INT, TYPE_CHARPTR };
struct variant_t
{
enum var_type;
union
{
int int_val;
char* charptr_val;
} var_value;
};
Here's an example of usage:
And when I run it...Code:itsme@dreams:~/C$ cat void.c
#include <stdio.h>
enum { STR_TYPE, INT_TYPE };
void func(void *ptr, int type)
{
switch(type)
{
case STR_TYPE:
printf("It's a str! The str is: %s\n", (char *)ptr);
break;
case INT_TYPE:
printf("It's an int! The int is: %d\n", *(int *)ptr);
break;
default:
printf("It's an unknown type!\n");
break;
}
}
int main(void)
{
char str[] = "Hello, world!";
int num = 86;
func(str, STR_TYPE);
func(&num, INT_TYPE);
return 0;
}
Quote:
itsme@dreams:~/C$ ./void
It's a str! The str is: Hello, world!
It's an int! The int is: 86
itsme@dreams:~/C$
Thanks people!