# Cuda Malloc Pitch Doubt on cudaMallocPitch()

**URL:** <https://forums.developer.nvidia.com/t/cuda-malloc-pitch-doubt-on-cudamallocpitch/26730>\
**Category:** CUDA Programming and Performance\
**Created:** [May 24, 2012, 5:20pm UTC](https://forums.developer.nvidia.com/t/cuda-malloc-pitch-doubt-on-cudamallocpitch/26730 "2012-05-24T17:20:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Waltee1000](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@Waltee1000](https://forums.developer.nvidia.com/u/Waltee1000)\
**Post date:** [May 24, 2012, 5:20pm UTC](https://forums.developer.nvidia.com/t/cuda-malloc-pitch-doubt-on-cudamallocpitch/26730/1 "2012-05-24T17:20:10Z")

</div>

Hello All,

Suppose I allocate memory for a 2D array using cudaMallocPitch(). Now say I want to access individual rows of the array. How do I use pitch to correctly access only a part of the array.

Is Array[j\*pitch] correct. if j is a variable that has the value 0,1,2,3…

Suppose pitch is 32, In that case the first row is at Array[0], Array[1]… so on  
the 2nd row start at Array[32], Array[33]… so on

Am I right?

Thanks in advance.

Regards,

Walter

---

<div class="post-metadata">

**Author:** ![njuffa](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@njuffa](https://forums.developer.nvidia.com/u/njuffa)\
**Post date:** [May 24, 2012, 7:13pm UTC](https://forums.developer.nvidia.com/t/cuda-malloc-pitch-doubt-on-cudamallocpitch/26730/2 "2012-05-24T19:13:10Z")

</div>

cudaMallocPitch() returns the pitch in bytes, as it has no notion of the size of the elements in the array. Depending on the size of each element the pitch may not even be an integral multiple of the element size, e.g. if each element is a struct of three ints. In the case where the element size in bytes is a power of two, you can trivially convert byte-pitch to element-pitch and use that in your 2D addressing:

```auto
int pitchInElems = (int)(pitch / sizeof(A[0]));

// access row-major A(i,j)

... = A[pitchInElems * i + j];

```

[Later:] Actually, the documentation for cudaMallocPicth() already shows how to address an element at (row,column) inside a 2D matrix stored in row-major mode and composed of elements of arbitrary type:

[http://developer.download.nvidia.com/compute/cuda/4\_2/rel/toolkit/docs/online/group\_\_CUDART\_\_MEMORY\_g80d689bc903792f906e49be4a0b6d8db.html#g80d689bc903792f906e49be4a0b6d8db](http://developer.download.nvidia.com/compute/cuda/4_2/rel/toolkit/docs/online/group __CUDART__ MEMORY_g80d689bc903792f906e49be4a0b6d8db.html#g80d689bc903792f906e49be4a0b6d8db)

```auto
T* pElement = (T*)((char*)BaseAddress + Row * pitch) + Column;

```
