# structures, pointers, and cudaMalloc/Memcpy

**URL:** <https://forums.developer.nvidia.com/t/structures-pointers-and-cudamalloc-memcpy/23789>\
**Category:** CUDA Programming and Performance\
**Created:** [August 3, 2011, 8:36am UTC](https://forums.developer.nvidia.com/t/structures-pointers-and-cudamalloc-memcpy/23789 "2011-08-03T08:36:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gurifisu](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@gurifisu](https://forums.developer.nvidia.com/u/gurifisu)\
**Post date:** [August 3, 2011, 8:36am UTC](https://forums.developer.nvidia.com/t/structures-pointers-and-cudamalloc-memcpy/23789/1 "2011-08-03T08:36:50Z")

</div>

Hi, I have the following matrix struct:

```auto
typedef struct {

   int width;

   int height;

   int pitch;

   float *elements;

} Matrix;

```

I’ve created the host matrix, and I’m not sure how to copy it over into the device. Here is my code:

```auto
Matrix * d_alloc_matrix(Matrix const * A) {

cudaError_t err;

Matrix *Md;

//Get the size of struct

    int size_m = sizeof(*A);

err = cudaMalloc((void **) & Md, size_m);

//cudaMemcpy sets Md->elements to point to the same address as that of in Host(which is wrong)

    cudaMemcpy(Md, A, size_m, cudaMemcpyHostToDevice);

//need to cudaMalloc a new chunk of memory in the device

    int size_e = A->width * A->height * sizeof(float);

float *temp_addr;

cudaMalloc((void**) &temp_addr, size_e);

//Copy over the elements to our device storage

    err = cudaMemcpy(temp_addr, A->elements, size_e, cudaMemcpyHostToDevice);

//Set the Md->elements pointers to point to the same address as of temp_addr

    err = cudaMemcpy(&(Md->elements), &temp_addr , sizeof(float *), cudaMemcpyDeviceToDevice);

return Md;

}

```

I have another piece of code that transfers the matrix back to host:

```auto
void copy_matrix_DeviceToHost(Matrix *Md, Matrix *Mh) {

    int size = Mh->height * Mh->width * sizeof(float);

    cudaMemcpy(Mh->elements, Md->elements, size, cudaMemcpyDeviceToHost);

}

```

I’m segfaulting =( . Any tips?

---

<div class="post-metadata">

**Author:** ![MarkusM](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@MarkusM](https://forums.developer.nvidia.com/u/MarkusM)\
**Post date:** [August 3, 2011, 9:27am UTC](https://forums.developer.nvidia.com/t/structures-pointers-and-cudamalloc-memcpy/23789/2 "2011-08-03T09:27:42Z")

</div>

You can’t access Md-\>elements because Md is on the device.  
Malloc Md on the host and only Md-\>elements on the device. You can then pass \*Md to kernels [post=‘1270181’]just like here[/post].
