CrispyCashew CrispyCashew - 1 month ago 16
C Question

Print void pointer in a Linked List

I have an array of structs called arrayOfElements , the structs are called Elements which have a void pointer

typedef struct {
void* data;
} Element;


Ive malloc'd arrayOfElements

Element* arrayOfElements;
arrayOfElements= malloc(4 * sizeof(Element));


and have stored ints and strings in the strucs

arrayOfElements[3].data = malloc( sizeof(int) );
ptr = arrayOfElements[3].data;
*ptr = 65;


strcpy(arrayOfElements[1].data, token );

Then I have created a Linked List

typedef struct LinkedList {
void* arrayOfStruct;
struct LinkedList* next;
} LinkedList;


And have created a function to import a instance of arrayOfELements and make void* arrayOfStruct point to it

LinkedList* insert(LinkedList* head, Element* inArrayOfElements)
{
LinkedList* insertNode = malloc(sizeof(LinkedList));
insertNode->next = head;
insertNode->arrayOfStruct = (void*)inArrayOfElements;
return insertNode;
}


Question

My question is after I have pointed void* arrayOfStruc to an instance of arrayOfELements, how do I print void* data of arrayOfElements[3] which I know from before is an int and its value is 65

Current Node in LinkedList ---> arrayOfElements[3] --> data member in Element struct (should equal 65)

I have a feeling I should point a int pointer to it and then print that, but Im not sure the syntax to do it

Answer

You need some way of knowing what kind of data the data member points to. An additional element denoting the type would work.

typedef enum {
    STR_TYPE,
    INT_TYPE,
    ...
} data_type;

typedef struct {
    data_type type;
    void* data;
} Element;

Then you can set the element like this:

arrayOfElements[3].type = INT_TYPE;
arrayOfElements[3].data = malloc( sizeof(int) );
int *ptr = arrayOfElements[3].data;
*ptr = 65;

arrayOfElements[1].type = STR_TYPE;
strcpy(arrayOfElements[1].data, token );

and read it like this:

Element *curr = &list_node->arrayOfStruct[3];
if (curr->type == INT_TYPE) {
    int *pint = curr->data;
    printf("int data = %d\n", *pint);
}
Comments