简体   繁体   English

两个具有不同类型的二维数组指向相同的内存

[英]Two bidimensional array with different types pointing to the same memory

I'm having a problem with pointers and array. 我有指针和数组的问题。

In delphi if I wanted to have a bidimensional array with multiple types but the same data (it would point to the same memory) I would use absolute : 在delphi中,如果我想要一个具有多种类型但具有相同数据的二维数组(它将指向相同的内存),我将使用绝对

arr_byte : array [1..2,1..80] of byte;
arr_word : array [1..2,1..40] of word absolute arr_byte;

So i could access the same data with different types (byte, word, dword etc). 所以我可以使用不同的类型(字节,字,双字等)访问相同的数据。

Now that i switched to C++ and QT5 I can't understand how to make it work for bidimensional array. 现在我切换到C ++和QT5,我无法理解如何使其适用于二维数组。 For a normal array I use 对于我使用的普通数组

quint16 Tab_Unsigned[100];

qint16  *Tab_Signed[100];

*Tab_Signed= Tab_Unsigned;

and then I use 然后我用

Tab_Unsigned[1]
(*Tab_Signed)[1]

to access the data, but I can't figure out how to do that for a two dimensional array. 访问数据,但我无法弄清楚如何为二维数组做到这一点。

Any tips ? 有小费吗 ?

EDIT: 编辑:

As Igor Sevo pointed out, union work wonderfully for that. 正如伊戈尔塞沃指出的那样,工会为此付出了奇妙的努力。

union Data
{
    qint16 q_int16[2][2];
    quint16 q_uint16[2][2];
    qint8 q_int8[2][4];
    quint8 q_int8[2][4];
};

union Data u_data;

u_data.q_int16[1][0] = -1;

qDebug() << u_data.q_uint16[1][0]; // prints  65535
qDebug() << u_data.q_int16[1][0];  // prints -1
qDebug() << u_data.q_int8[1][0];    // prints -1
qDebug() << u_data.q_int8[1][1];    // prints -1
qDebug() << u_data.q_uint8[1][0];   // prints 255
qDebug() << u_data.q_uint8[1][1];   // prints 255

wich is exactly what I was looking for ! 这正是我想要的!

Two dimensional arrays in C are actually one dimensional arrays with different indexing. C中的二维数组实际上是具有不同索引的一维数组。 You could use a function to determine the index in the array from the matrix indices. 您可以使用函数从矩阵索引中确定数组中的索引。 For example, you could use index=i*n+j for finding the index. 例如,您可以使用index=i*n+j来查找索引。

You could also try using a union . 您也可以尝试使用联合

You have arrays of arrays in C/C++: 你有C / C ++中的数组数组:

quint16 BiUnsigned[100][10];
// ...
qint16 **BiSigned = static_cast<qint16**>(BiUnsigned);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM