title: CUDA 2d array addressing within kernel
body: <p>I have seen plenty of questions regarding it but none solved my problem.</p>
  
  <p>I copy an initialized array of size n x n to global device memory as a 2D array, run some kernel and copy it back:</p>
  
  <pre><code>int image_width = 5;
  int image_height = 4;
  int n = image_height*image_width;
  int *G = (int *) malloc (sizeof(int) * n*n);
  size_t pitch;
  int *dev_d = 0;
  
  for (int x =0; x&lt;n*n;x++) G[x] = 9;
  
  cudaError_t cudaStatus = cudaMallocPitch(&amp;dev_d, &amp;pitch, n * sizeof(int), n);
  cudaStatus  = cudaMemcpy2D(dev_d, pitch, G, n * sizeof(int), n * sizeof(int), n, cudaMemcpyHostToDevice); //A
  
  setup_adjacency_matrix&lt;&lt;&lt;4, 2&gt;&gt;&gt;(n, dev_d, image_width,pitch);
  cudaStatus = cudaMemcpy2D(d, n * sizeof(int), dev_d, pitch, n * sizeof(int), n, CMCPYDTH); //copy back  //B
  HANDLE_ERROR(cudaStatus);
  </code></pre>
  
  <p>For testing purposes I just want 4 blocks of 2 threads each. The test kernel itself also does not do anything particular:</p>
  
  <pre><code>__global__ void setup_adjacency_matrix(
      const unsigned int V,  int * const d,const unsigned int image_width,size_t pitch){
       d[blockIdx.x*V+threadIdx.x] = blockIdx.x*100+threadIdx.x; //problem here?
  }
  </code></pre>
  
  <p>But the only threads from the first block seem to affect the array as the result is:</p>
  
  <pre><code>0 1 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
  </code></pre>
  
  <p>All works fine when i use th 1d array and do the copying in lines A and B like: </p>
  
  <pre><code> cudaMemcpy(dev_d, G,  n * sizeof(int)* n, cudaMemcpyHostToDevice); //A
   cudaStatus = cudaMemcpy(d,  dev_d, n * sizeof(int)* n, CMCPYDTH); //B
  </code></pre>
  
  <p>But i want to learn using the 2d arrays!
  I am guessing the way I calculate the address of the array elements is wrong, and I also tried to multiply it by pitch like <code>d[blockIdx.x*V*pitch+threadIdx.x] = blockIdx.x*100+threadIdx.x;</code>, but did not manage to get a better result. What am I doing wrong? Please help!</p>