NISHIT KHARA
NISHIT KHARA

Reputation: 63

Dynamically allocate Multi-dimensional array of structure using C++

For a school project, I'm trying to dynamically declare an array of structures with the rows and cols as inputs from the command line interface. I've been reading about pointer to pointer concepts and want to know is my definition correct with respect to what I need. So basically I need an array of structures which can be expanded dynamically with respect to both rows and cols. I've done this so far.

In the global scope

struct st2_D
{
uint8_t ucvar1;
uint32_t ui32var2; 
}
st2_D ** ppst2_D;

In main(), I've the following definition:

ppst2_D = new st2_D * [rows]
for(uint32_t var = 0; var < rows; var++) ppst2_D[var] = new st2_d[cols]

So will this create an array of structures with the given rows and cols? Also, how will I access the elements of the structure at a particular row and col?

Upvotes: 1

Views: 88

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

These statements

ppst2_D = new st2_D * [rows]
for(uint32_t var = 0; var < rows; var++) ppst2_D[var] = new st2_d[cols]

create a one-dimensional array of pointers to the type st2_D. And then rows one-dimensional arrays of the type ppst2_D[var] are created.

You can use either indices as with usual two-dimensional arrays as for example

ppst2_D[i][j]

Or you can use for example the pointer arithmetic as for example

*( *( ppst2_D + i ) + j )

or even their combinations as for example

( *( ppst2_D + i ) )[j]

or

*( ppst2_D[i] + j )

Here is a demonstrative program.

#include <iostream>
#include <iomanip>

int main() 
{
    size_t n = 5;
    int **a = new int *[n];

    for ( size_t i = 0; i < n; i++ )
    {
        a[i] = new int[n];
    }

    for ( int **p = a; p != a + n; ++p )
    {
        for ( int *q = *p; q != *p + n; ++q )
        {
            *q = q - *p + ( p - a ) * n;
        }
    }

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < n; j++ )
        {
            std::cout << std::setw( 2 ) << a[i][j] << ' ';
        }

        std::cout << '\n';
    }

    for ( size_t i = 0; i < n; i++ )
    {
        delete [] *( a + i );
    }

    delete [] a;

    return 0;
}

Its output is

 0  1  2  3  4 
 5  6  7  8  9 
10 11 12 13 14 
15 16 17 18 19 
20 21 22 23 24 

Upvotes: 1

Related Questions