title: C automatic-expandable array of pointers
body: <p><strong>QUESTION ANSWERED AT END OF PAGE. FULLY WORKING CODE.</strong></p>
  
  <p>Hello, I would like to do in C what I have asked in the title, however, I don't know how to accomplish it. I have done this in C++ thanks to templates but <em>à la C</em>. Here is the fully functional C++ code: <a href="http://sourceforge.net/projects/toolsopengl/files/List.h/download" rel="nofollow">List.h (simple database)</a></p>
  
  <p>*<em>I wonder now if with void pointers I can emulate the code. The problem is that I've seen a link stating that void *</em> should be avoided because it can cause more trouble than it can solve.</p>
  
  <p>Basically it is a "smart-array" that stores pointers to the variables themselves.
  If I know the size of each pointer and the size of each structure pointed to, simple mallocs and reallocs should do right?</p>
  
  <pre><code>typedef struct
  {
    void **list;
  
    // internal
    int last_item_index;
    size_t element_size; // size of each pointer
    int elements;        // number of currently allocated elements
    int total_size;      // &gt;= #elements so that we don't have to always call malloc
    int tweak_request_size; // each time the list grows we add this # of elements
  
  } List;
  // a shot at an addCopy function
  // it deepcopies the object you pass in
  List_addCopy(List *db, void *ptr_to_new_element)
  {
    ... // grow **list
    // alloc and copy new element
    db-&gt;list[db-&gt;last_item_index+1] = malloc(element_size); // WORKS?
    // HOW TO COPY THE ELEMENT TO HERE IF IT IS A STRUCTURE FOR INSTANCE???
    ...
  }
  
  or
  // a shot at an assign function 
  // (allocate the elements yourself then pass the pointer to the List)
  List_assign(List *db, void *ptr_to_new_element)
  {
    db-&gt;List = realloc(db-&gt;List, element_size*(elements+tweak_request_size));
    db-&gt;List[db-&gt;last_item_index+1] = ptr_to_new_element;
  }
  
  // Usage example
  
  List db; // our database
  struct funky *now = (funky*)malloc(sizeof(funky));
  
  funky-&gt;soul = JamesBrown;
  
  List_addCopy(db, funky);
  
  if (list[0]-&gt;soul == JamesBrown)
    puts("We did It! :D");
  </code></pre>
  
  <p>If I alloc everything outside and just pass the pointers to the List I guess the only problem is the void **.</p>
  
  <p>Is List_add possible? Only with callbacks that do the alloc of the element and / or copy it?</p>
  
  <p>Is List_assign possible? I don't want to have a lot of work and end up with unreliable software.</p>
  
  <p>Thanks a lot and sorry for the convolution in the writing :p</p>