What I'm trying to do is store values in a array of Element struczs (that has a member void* data)
typedef struct {
void* data
} Element;
I have malloc'd the array to have 3 elements
Element* array = malloc(3 * sizeof(Element));
I know you can do it like this if data is a int but how do you do it if data is void *
array[0].data = 65;
I've tried typecasting
((*int)(array[0].data)) = 65;
but I get the message expected expression before 'int'
My second question is how would I go about storing a string in the Element struct (I can't make another member that is a string it has to be using the void pointer)
Can I use strcopy or sscanf ?
Sample main below in case I'm doing something wrong
#include "test.h"
int main (void)
{
Element* array = malloc(3 * sizeof(Element));
((*int)(array[0].data)) = 65;
((*int)(array[1].data)) = 64;
((*int)(array[2].data)) = 66;
}
EDIT
Sorry I should have added that the data will be added using a loop (the iterations is based on user input, so arrayOfElements could have 5,8,20 ect elements), based on user3386109 answer
Element* arrayOfElements = malloc(3 * sizeof(Element));
arrayOfElements[0].data = malloc( sizeof(int) );
int *ptr = arrayOfElements[0].data;
*ptr = 65;
work perfectly but if I want to make arrayOfElements[1].data = 67
Element* arrayOfElements = malloc(3 * sizeof(Element));
arrayOfElements[1].data = malloc( sizeof(int) );
int *ptr = arrayOfElements[1].data;
*ptr = 76;
I can't reuse *ptr even if I do free(ptr) , is there anyway to do this if you don't know how many elements arrayOfElements will have?
void*for any purpose, you must have a plan for how to know what types it points to, or your program will not doing anything useful. You store misc types through avoid*then what? How will you know what each such pointer points at? - Lundin