Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two bidimensional array with different types pointing to the same memory

Tags:

c++

delphi

qt5

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 :

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. 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 !

like image 296
Manuel Cortelletti Avatar asked Jul 09 '26 07:07

Manuel Cortelletti


1 Answers

Two dimensional arrays in C are actually one dimensional arrays with different indexing. 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.

You could also try using a union.

like image 156
Igor Ševo Avatar answered Jul 10 '26 20:07

Igor Ševo