Initialize void pointer to point to an array

Posted by idealistikz on Stack Overflow See other posts from Stack Overflow or by idealistikz
Published on 2010-04-24T17:35:45Z Indexed on 2010/04/24 17:43 UTC
Read the original article Hit count: 109

Filed under:

Suppose I have the following:

typedef struct {
   int itemSize;
   int count;
   void *list;
} Mystruct;

Mystruct *InitStruct(int itemSize, int count) 
{
  Mystruct *my = malloc(sizeof(Mystruct));
  my->itemSize = itemSize;
  my->count = count;
  //What is the best way to initialize list?  For example:
  //my->list = malloc(count * sizeof(void *));   OR
  //my->list = malloc(count * sizeof(itemSize));
}

//The following should return a pointer to the element stored at a given index 
void *Retrieve(const MyStruct *my, int index)
{
   void *item;
   //What is the best way to return a pointer to the item at the given index from 
   //my->list?
}

Mystruct is similar to an array and void *list is supposed to store the elements or pointers to the elements. Mystruct *InitStruct is a function that initializes a Mystruct pointer and void *Retrieve is a function that returns a pointer to the element stored at a given index.

First, how should I initialize void* list? Should it hold the actual elements or be an array of pointers pointing to the elements?

Second, using the void *Retrieve function, how do I return a pointer to the element stored at a given index in my->list?

© Stack Overflow or respective owner

Related posts about c