Home > OS >  Problem with casting pointers from one structure to another structure?
Problem with casting pointers from one structure to another structure?

Time:01-11

I'm trying to cast the address of individual array components into another structure

Here are the structures:

#define ADDRESS_SPACE 8

struct dma_engine
{
    int *Address[ADDRESS_SPACE] = {nullptr};
};

struct data_engine
{
    int data[ADDRESS_SPACE] = {0x10,0x14,0x18,0x1B,0x20,0x24,0x28,0x2B};
};

Its working when I do each array component individually, like that:

dma_engine  Dma_0;
data_engine Data_0;

Dma_0.Address[0] = (int*) &Data_0.data[0];
Dma_0.Address[1] = (int*) &Data_0.data[1];
Dma_0.Address[2] = (int*) &Data_0.data[2];
Dma_0.Address[3] = (int*) &Data_0.data[3];
Dma_0.Address[4] = (int*) &Data_0.data[4];
Dma_0.Address[5] = (int*) &Data_0.data[5];
Dma_0.Address[6] = (int*) &Data_0.data[6];
Dma_0.Address[7] = (int*) &Data_0.data[7];

But when I'm trying to pass everything at once, like that:

dma_engine  Dma_0;
data_engine Data_0;

Dma_0.Address = (int*) &Data_0.data;

I receive the following compilation ERROR:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:30:36: error: incompatible types in assignment of ‘int*’ to ‘int* [8]’
   30 |     Dma_0.Address = (int*) &Data_0.data;

Also, doesn't work when I try this way:

dma_engine  Dma_0;
data_engine Data_0;

Dma_0.Address = &Data_0.data;

I receive this ERROR !

main.cpp: In function ‘int main(int, char**)’:
main.cpp:30:36: error: incompatible types in assignment of ‘int*’ to ‘int* [8]’
   30 |     Dma_0.Address = (int*) &Data_0.data;

Can someone please help me with this?

Many Thanks

CodePudding user response:

You need to change Address to be a pointer to int[ADDRESS_SPACE]:

#define ADDRESS_SPACE 8

struct dma_engine {
    int (*Address)[ADDRESS_SPACE] = nullptr;  // correct type
};

struct data_engine {
    int data[ADDRESS_SPACE] = {0x10, 0x14, 0x18, 0x1B, 0x20, 0x24, 0x28, 0x2B};
};

int main() {
    dma_engine Dma_0;
    data_engine Data_0;

    Dma_0.Address = &Data_0.data; // no cast here
}

or just a plain int*:

#define ADDRESS_SPACE 8

struct dma_engine {
    int *Address = nullptr;  // int*
};

struct data_engine {
    int data[ADDRESS_SPACE] = {0x10, 0x14, 0x18, 0x1B, 0x20, 0x24, 0x28, 0x2B};
};

int main() {
    dma_engine Dma_0;
    data_engine Data_0;

    Dma_0.Address = Data_0.data; // still no cast here, but don't take the address
}
  •  Tags:  
  • Related