title: Dereferencing pointer to array of void
body: <p>I am attempting to learn more about C and its arcane hidden powers, and I attempted to make a sample struct containing a pointer to a void, intended to use as array.
  EDIT: Important note: This is for raw C code.</p>
  
  <p>Let's say I have this struct.</p>
  
  <pre><code>    typedef struct mystruct {
          unsigned char foo;
          unsigned int max;
          enum data_t type;
          void* data;
  
      } mystruct;
  </code></pre>
  
  <p>I want data to hold <em>max</em> of either unsigned chars, unsigned short ints, and unsigned long ints, the data_t enum contains
   values for those 3 cases.</p>
  
  <pre><code>    enum Grid_t {gi8, gi16, gi32}; //For 8, 16 and 32 bit uints.
  </code></pre>
  
  <p>Then I have this function that initializes and allocates one of this structs, and is supposed to return a pointer to the new struct.</p>
  
  <pre><code>    mystruct* new(unsigned char foo, unsigned int bar, long value) {
          mystruct* new;
          new = malloc(sizeof(mystruct)); //Allocate space for the struct.
          assert(new != NULL);
          new-&gt;foo = foo;
          new-&gt;max = bar;
          int i;
          switch(type){
              case gi8: default:
                  new-&gt;data = (unsigned char *)calloc(new-&gt;max, sizeof(unsigned char));
                  assert(new-&gt;data != NULL);
                  for(i = 0; i &lt; new-&gt;max; i++){
                      *((unsigned char*)new-&gt;data + i) = (unsigned char)value;
                      //Can I do anything with the format new-&gt;data[n]? I can't seem
                      //to use the [] shortcut to point to members in this case!
                  }
              break;
          }
          return new;
      }
  </code></pre>
  
  <p>The compiler returns no warnings, but I am not too sure about this method. Is it a legitimate way to use pointers?</p>
  
  <p>Is there a better way©?</p>
  
  <p>I missed calling it. like mystruct* P; P = new(0,50,1024);</p>
  
  <p>Unions are interesting but not what I wanted. Since I will have to approach every specific case individually anyway, casting seems as good as an union. I specifically wanted to have much larger 8-bit arrays than 32-bits arrays, so an union doesn't seem to help. For that I'd make it just an array of longs :P</p>