Nazar
Nazar

Reputation: 880

Create a pointer to an array of pointers to arrays of structs and then access the variable in a struct

I think I got the general idea of how to create and destroy it, but I can not find the way to access each of the objects. Here's how I create it:

CCyIsoPktInfo   **arrayOfPointers = new CCyIsoPktInfo*[QueueSize];
for (int i = 0; i < QueueSize; ++i)
{
     arrayOfPointers[i] = new CCyIsoPktInfo[PACKETS_PER_TRANSFER];
}

Here's how I destroy it:

for (int i = 0; i < QueueSize; ++i)
{
    delete[] arrayOfPointers[i];
}
delete[] arrayOfPointers;

But I need to access each nth_Object.status in the array, given the nth_Pointer to that array. So the general idea would be like this:

for (int nth_Object = 0; nth_Object < PACKETS_PER_TRANSFER; ++nth_Object)
{
    var[nth_Object] = (*arrayOfPointers[nth_Pointer]).[nth_Object].status;
}

I am creating and destroying the them properly? How to access the elements?

Upvotes: 1

Views: 191

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 118021

To iterate over your 2D array, you would use a nested loop, for example

for (int nth_Object = 0; nth_Object < QueueSize; ++nth_Object)
{
    for (int nth_Pointer = 0; nth_Pointer < PACKETS_PER_TRANSFER; ++ nth_Pointer)
    {
        std::cout << arrayOfPointers[nth_Object][nth_Pointer].status;
    }
}

Although for what it's worth, I would recommend using std::vector instead of dynamically allocating your own arrays

std::vector<std::vector<CCyIsoPktInfo>> data;

Then you could iterate like

for (auto const& row : data)
{
    for (auto const& element : row)
    {
        std::cout << element.status;
    }
}

Upvotes: 1

Related Questions