Afficher un message
Vieux 11/04/2008, 14h39   #2
Sebastian Morawietz
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut 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;
}


  Réponse avec citation
 
Page generated in 0,04958 seconds with 9 queries