title: How to delete and reassign a dynamically allocated pointer
body: <p>I'm taking a c++ programming course (we are still mostly using C) and we just got to dynamic allocation of memory. For one of my homeworks, I'm asked to create a function that transposes any given matrix. This function is given the following arguments as inputs: a pointer, in which are saved the matrix elements, the number of rows and of colunms. I would like this to be a <em>void</em> type function that changes the order of the stored elements without returning any new pointer.
  I tried creating a new pointer, in which I save the elemtens in the correct order (using 2 <em>for</em> loops). Then what I would like to do is deallocating the original pointer (using the <code>delete</code> command), assinging it to the new pointer and finally deleting the new pointer.
  This unfortunately does not work (some elements turn out to be random numbers), but I don't understand why.
  I hope my code is more precise and clear than my explanation:</p>
  <pre><code>void Traspose(float *matrix, const int rows, const int cols ){
  
      auto *tras = new float [rows * cols];
      int  k = 0;
  
      for(int i = 0; i &lt; cols; i++){
          for(int j = 0; j &lt; rows * cols; j += cols){
              tras[k] = matrix[j + i];
              k++;
          }
      }
  
      delete[] matrix;
      matrix = tras;
      delete[] tras;
  }
  </code></pre>