title: Assigning an address to a struct pointer array member in C
body: <p>Having considerable trouble with some pointer arithmatic. I <em>think</em> I get the concepts (pointer variables point to a memory address, normal variables point to data) but I believe my problem is with the syntax (<code>*, &amp;, (*), *(),</code> etc.)</p>
  
  <p>What I want to do is build dynamic arrays of a custom struct (i.e. arrays of pointers to heap structs), and my interface provides two methods, "ad_to_obj_array" (which takes the object to add and the array which can be null for empty) and "obj_array_dustbin" (which just takes the array to dispose, also disposing of the contents, the heap objs). The former is rendered below.</p>
  
  <p>The details of the objects are not important (and the struct has been renamed anyway) but my solution to the general problem is below, and I'd be grateful if you can spot the error. The compiler is complaining about an invalid lvalue, where I try and assign the address in the pointer on the RHS to the pointer value in an array of pointers to heap structs:</p>
  
  <pre><code>#define NUM_ELEM(x) (sizeof (x) / sizeof (*(x)))
  
  obj* add_to_obj_array(obj* new_obj, obj* array)
  {
    int number_of_elements = 0;
    if (array != NULL)
    {
      number_of_elements = NUM_ELEM(array);
    }
  
    obj* new_array = NULL;
  
    /* note: I am expecting sizeof(new_obj) to return the size of an obj* 
       to go into the array of pointers. */
    if ( NULL ==
         (new_array = (obj*)malloc((number_of_elements + 1)* sizeof(new_obj))) )
    {
      /* memory request refused :( */
      return NULL;
    }
  
    /* copy the old array pointers into the new array's pointer slots: */
    int i;
    for (i = 0; i &lt; number_of_elements; i++)
    {
      &amp;(new_array[i]) = &amp;(array[i]);
    }
  
    /* add the new item to the end (assign pointer value directly): */
    new_array[number_of_elements] = new_obj;
  
    if (number_of_elements &gt; 0)
    {
      free(&amp;array);
    }
  
    return new_array;
  }
  </code></pre>
  
  <p>Now, I have tried the following permutations of the offending line:</p>
  
  <pre><code>  &amp;(new_array[i]) = &amp;(array[i]);
    *(new_array[i]) = &amp;(array[i]);
    new_array[i] = &amp;(array[i]);
  </code></pre>
  
  <p>and all give a compiler error of one sort or another. I am fairly sure that the right hand side is the address of the ith element of the old array, but how to I assign to the ith element of the new, when the elements of the array are pointers to structs?</p>
  
  <p>EDIT - please note, the macro NUM_ELEM above DOES NOT WORK; it will always return 1. See @Merlyn Morgan-Graham's answer below for why.</p>