title: Setting Dynamic arrays equal to eachother in C
body: <pre><code>int staticArrayA[10];
  int staticArrayB[10];
  int *dynamicArrayA = (int *)malloc(sizeof(int) * 10);
  int *dynamicArrayB = (int *)malloc(sizeof(int) * 10);
  </code></pre>
  
  <p>From what I understand, the value of staticArrayA is a pointer to the 1st element in the array, however the pointer that represents this base address behaves like a const pointer and cannot be changed, in which case it makes sense that you cannot set: </p>
  
  <pre><code>staticArrayA = staticArrayB;
  </code></pre>
  
  <p>But what about dynamic arrays? if they are both just pointers to a contiguous block of bytes in memory, then why can't you set them equal to eachother?</p>
  
  <pre><code>dynamicArrayA = dynamicArrayB;
  </code></pre>
  
  <p>It seems like the address that dynamicArrayA points to would now be the same address that dynamicArrayB points to. Please give me some insight. Perhaps I am wrong, but here is what I was trying to do:</p>
  
  <pre><code>/* remove any element that is 0 from array. n is size of array */
  void compressArray(int *array, int n) {
      int size = n;
      int index = 0;
      int *nuArray = (int *)malloc(sizeof(int) * n);
      assert(nuArray != NULL);
      for (int i = 0; i &lt; n; i++) {
          if (array[i] != 0) {
              nuArray[index] = array[i];
              index++;
              size--;
          }
      }
      nuArray = realloc(nuArray, sizeof(int) * size);
      assert(nuArray != NULL);
      array = realloc(array, sizeof(int) * size);
      assert(array != NULL);
      array = nuArray; //This doesn't seem to work
      free(nuArray);
  }
  
  int main(int argc, const char * argv[]) {
      int *array = (int *)malloc(sizeof(int) * 10);
      assert(array != NULL);
      for (int i = 0; i &lt; 10; i++) {
          if (i % 2 == 0) {
              array[i] = 0;
          } else {
              array[i] = i;
          }
      }
      compressArray(array, 10);
      return 0;
  }
  </code></pre>
  
  <p>I am sure that there are much simpler and more elegant ways to write the function, and i know that I can copy all the elements of nuArray into array and then use realloc() to reduce the size, however, I am just hoping someone can give some insight into the nature of dynamic arrays and explain some of this behavior and tell me why the assignment does not work, or if there are cases in which it does. Also, i could have the function return an int * and set array = to this function call and that works, however why can't i do it inside the function? Thanks for your time and for any help.</p>