1

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?

Nazar
  • 820
  • 5
  • 13
  • 36
  • FWIW I would suggest either `std::array, 64>` or `std::vector> – Cory Kramer Sep 04 '15 at 19:52
  • Hey @CoryKramer , I am trying to adopt the answer you referenced as duplicate, do not know if I will make it right. Also, I am not familiar with the coding style you suggested. – Nazar Sep 04 '15 at 19:59
  • What you want is: CCyIsoPktInfo * (* p_to_arr_of_pts) [num]. C++ attempts to follow C's "declaration mimicks usage" pattern. Also, take note that in the line you provided, you do not create an array of pointers to CCyIsoPktInfo objects but instead an array of CCylsoPktInfo objects. – Veritas Sep 04 '15 at 20:30
  • @Veritas oh, then _num_ is what 64 or 256? And where does the other number goes? – Nazar Sep 04 '15 at 20:50
  • @CoryKramer you marked my question as a duplicate, but the answers you referenced to do not answer my question completely. What now? I am doomed. – Nazar Sep 08 '15 at 13:31

1 Answers1

1

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;
    }
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Cory, for clean up, is it necessary to loop through the array of pointers `delete[] arrayOfPointers[i]` and `delete[] arrayOfPointers` and delete each pointer in the array, or `delete[] arrayOfPointers` is enough? – Nazar Sep 08 '15 at 20:53
  • Yes you must clean up the memory as you've shown in your initial post. – Cory Kramer Sep 09 '15 at 11:05