# How to access the data of a Tensor

**URL:** <https://discuss.pytorch.org/t/how-to-access-the-data-of-a-tensor/199185>\
**Category:** C++\
**Created:** [March 19, 2024, 2:06pm UTC](https://discuss.pytorch.org/t/how-to-access-the-data-of-a-tensor/199185 "2024-03-19T14:06:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sroyyors](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/sroyyors/32/55214_2.png) [@sroyyors](https://discuss.pytorch.org/u/sroyyors)\
**Post date:** [March 19, 2024, 2:06pm UTC](https://discuss.pytorch.org/t/how-to-access-the-data-of-a-tensor/199185/1 "2024-03-19T14:06:22Z")

</div>

Hi,  
I wanted to directly access the data matrix of the Tensor to store in a primary type, e.g.a double array. I was doing this to write the Tensor to a binary file. Following this post [Convert tensor into an array](https://discuss.pytorch.org/t/convert-tensor-into-an-array/56721) I tried

```auto
 torch::Tensor preds = torch::zeros({ 4,8 });
        preds.index_put_({0,1},2);
        preds.index_put_({0,3},4);
        preds.index_put_({1,7},5);
        preds.index_put_({2,5},-5);
        preds.index_put_({3,6},-3.96);
        preds.index_put_({2,6},-1e-3);
       double* mydata=preds.data_ptr<double>();

```

But I get sigabort every time I do this. Any ideas how to address this?  
thanks!

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [March 19, 2024, 5:09pm UTC](https://discuss.pytorch.org/t/how-to-access-the-data-of-a-tensor/199185/2 "2024-03-19T17:09:37Z")

</div>

You could try to initialize or transform the tensor to `double` as the default `dtype` would be `float` (i.e. `float32`).

---

<div class="post-metadata">

**Author:** ![sroyyors](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/sroyyors/32/55214_2.png) [@sroyyors](https://discuss.pytorch.org/u/sroyyors)\
**Post date:** [March 19, 2024, 7:12pm UTC](https://discuss.pytorch.org/t/how-to-access-the-data-of-a-tensor/199185/3 "2024-03-19T19:12:01Z")

</div>

Thank you that worked! I did it like

```auto
torch::Tensor preds = torch::zeros({ 4,8 }).to(torch::kDouble);

```

However, I noted that although this is a 2d tensor, the data\_ptr will only return a double\* pointer. So I always have to do this:

```auto
double* mydata1d=preds.data_ptr<double>();

```

which I would read as a 1D array. I wonder if it is possible to read it in as a 2D array.

That said, I realized I can also just write the Tensor directly to a binary file like

```auto
mytensorfile.write(reinterpret_cast<char*>(&preds),4*8*sizeof(torch::kDouble));

```
