title: Allocate 2D array with cudaMallocPitch and copying with cudaMemcpy2D
body: <p>I'm new in CUDA, I appreciate your help and hope you can help me.</p>
  
  <p>I need to store multiple elements of a 2D array into a vector, and then work with the vector, but my code does not work well, when I debug, I find a mistake in allocating the 2D array in the device with <code>cudaMallocPitch</code> and copying to that array with <code>cudaMemcpy2D</code>. This is my code:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;cuda.h&gt;
  #include &lt;cuda_runtime.h&gt;
  #include &lt;cmath&gt;
  
  #define maxThreads 96
  
  __global__ void extract(int mSize, float* dev_vector, float* dev_matrix, int N)
  {
      int idx = threadIdx.x + blockIdx.x * blockDim.x;
  
      while(idx&lt;N)
      {
          dev_vector[idx] = *(dev_matrix+(mSize*idx+N));
          idx += blockDim.x * gridDim.x;
      }
  }
  
  int main()
  {
      //CPU variables
      int mSize = 5;
      float* matrix;
      int N = 4; // Vector size
      int i,j;
      float* vector;
      int blocks, threads;
  
      float* dev_matrix;
      float* dev_vector;
  
      blocks = 1+((N-1)/maxThreads);
      threads = 1+((N-1)/blocks);
  
      unsigned long int pitch;
      unsigned long int memsize_vector = N*sizeof(float);
      unsigned long int memsize_matrix = mSize*sizeof(float);
  
  
      matrix = new float[memsize_matrix*memsize_matrix];
      vector = new float[memsize_vector];
  
      //Create 2D array
      for(i=0; i&lt;mSize; i++)
          for(j=0; j&lt;mSize; j++)
          {
              matrix[i+mSize*j] = ((i+1)+(j+1));
          }
  
      printf("\n");
      for (i=0; i&lt;mSize; i++){
          for(j=0; j&lt;mSize; j++){
              printf("% 1.5f ", matrix[i+mSize*j]);
          }
          printf("\n");
      }
      printf("\n");
  
  
      cudaMallocPitch((void **)&amp;dev_matrix, &amp;pitch, memsize_matrix, mSize);
      cudaMalloc((void **)&amp;dev_vector, memsize_vector);
  
      cudaMemcpy2D(dev_matrix, pitch, matrix, memsize_matrix, memsize_matrix, mSize,
                       cudaMemcpyHostToDevice);
  
      extract&lt;&lt;&lt;blocks,threads&gt;&gt;&gt;(mSize, dev_vector, dev_matrix, N);
      cudaDeviceSynchronize();
  
      cudaMemcpy(vector, dev_vector, memsize_vector, cudaMemcpyDeviceToHost);
  
      printf("Vector values are:\n");
      for(i=0; i&lt;N; i++)
          printf(" % 1.5f ", vector[i]);
      printf("\n");
  
      cudaFree(dev_matrix);
      cudaFree(dev_vector);
  
  }
  </code></pre>