Re: Storing integer values in a void*
Hi there,
how about using a union and a type variable, instead of just a
pointer?
Hope this s
Seb
-------------------
#include <stdio.h>
#include <stdlib.h>
#define VALUE_TYPE_POINTER (1)
#define VALUE_TYPE_FLOAT (2)
#define VALUE_TYPE_INT (3)
typedef int value_type_t;
typedef struct node_t
{
value_type_t type;
union {
int intValue;
float floatValue;
void* pointerValue;
} value;
} node_t;
node_t*
node_new_with_pointer( void* value )
{
node_t* result = calloc( 1, sizeof( node_t ) );
result->type = VALUE_TYPE_POINTER;
result->value.pointerValue=value;
return result;
}
node_t*
node_new_with_int( int value )
{
node_t* result = calloc( 1, sizeof( node_t ) );
result->type = VALUE_TYPE_INT;
result->value.intValue=value;
return result;
}
int
main()
{
node_t* node = node_new_with_int( 17 );
printf( "node is an int type: %s\nValue: %i\n",
node->type == VALUE_TYPE_INT ? "true" : "false",
node->value.intValue );
free(node );
char* test="blahblah";
node=node_new_with_pointer( test );
printf( "node is a pointer-type: %s\n"
"Pointer is equal to test: %s\n",
node->type == VALUE_TYPE_POINTER ? "true" : "false",
test == node->value.pointerValue ? "true" : "false" );
free( node );
return 0;
}
|