1

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

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that, i didnt even think of setting a type variable. Is &list_node a pointer to the current node im in? ( or what ever node I want to read from) , so then curr points to arrayOfStruct[3] ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.