title: Fastest way to copy several 2-dimensional arrays into one 1-dimensional array (in C)
body: <p>I want to copy several 2-dimensional subarrays of 3-dimensional arrays (e.g. array1[n][rows][cols], ..., array4[n][rows][cols]), which are dynamically allocated (but with fixed length), into a 1-dimensional array (e.g. array[4*rows*cols]), which is statically allocated, in C. As there will be many rows and columns (e.g. 10000 rows and 500 columns), I was wondering which of the following three possibilities will be the fastest:</p>
  
  <pre><code>    for(i=0;i&lt;rows;i++){
        for(j=0;j&lt;cols;j++){
          array[i*cols+j]=array1[2][i][j];
        }
      }
      ...
      for(i=0;i&lt;rows;i++){
        for(j=0;j&lt;cols;j++){
          array[3*rows*cols+i*cols+j]=array4[2][i][j];
          }
      }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>    for(i=0;i&lt;rows;i++){
        for(j=0;j&lt;cols;j++){
          array[i*cols+j]=array1[2][i][j];
        }
        ...
        for(j=0;j&lt;cols;j++){
          array[3*rows*cols+i*cols+j]=array4[2][i][j];
        }
      }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>    for(i=0;i&lt;rows;i++){
        for(j=0;j&lt;cols;j++){
          array[i*cols+j]=array1[2][i][j];
          ...
          array[3*rows*cols+i*cols+j]=array4[2][i][j];
        }
      }
  </code></pre>
  
  <p>Or is there even a faster way of performing this task in C (not C++)?</p>
  
  <p>Thanks a lot! (I thought there should be a similar question already, but unfortunately did not find exactly what I was looking for. So, I am sorry if I missed such a question.)</p>
  
  <p>Edit:
  The reason for wanting to do this is the following: The information stored in those 2-dimensional (sub-)arrays has to be communicated via MPI. So, clients will do the above and the master (kind of) the other way round (i.e. 1-dimensional -> 2-dimensional). So, is there even a better way to do this overall?</p>