user4568872
user4568872

Reputation:

Get element of two-dimensional array with pointers

Have a problem. For example i have a code

class A
{
public:
int **p;
const int size=4;
A()
{
    p=new int*[size];
    for(int i = 0 ; i<size;i++)
    {
        p[i]=new int[size];
    }

    for(int i = 0 ;i<size*size;i++)
    {
        *(*p+i)=0;
    }
}
};

Then i create dynamic object of class A *matrix=new A; How can i get public access to **p ? I know how do it with function :

int A::GetElement(int position)
{
 return *(*p+position);
}

but interesting how do it with simple way. I tried matrix->*(*p+i) but it didnt work.

Upvotes: 0

Views: 36

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21619

Just use 2 indexes, for the 2 indexes of the array.

#include <iostream>

class A
{
public:
int **p;
const int size=4;
A()
{
    p=new int*[size];
    for(int i = 0 ; i<size;i++)
    {
        p[i]=new int[size];
    }

    for(int i = 0 ;i<size*size;i++)
    {
        p[i / 4][i % 4] = 16 - 1 - i;
    }
}
~A()
{

    for(int i = 0 ; i<size;i++)
    {
        delete[] p[i];
    }
    delete[] p;
}
};

int main(int, char**)
{
    A* a = new A();

    int i, j;
    for(i = 0; i < a->size; i++)
    {
        for(j = 0; j < a->size; j++)
        {
            std::cout << a->p[i][j] << '\n';
        }
    }

    for(i = 0; i < a->size; i++)
    {
        for(j = 0; j < a->size; j++)
        {
            std::cout << *(*(a->p + i) + j) << '\n';
        }
    }

    for(int i = 0 ;i<(a->size * a->size);i++)
    {
        std::cout << *(*(a->p + (i / a->size)) + (i % a->size)) << '\n';
    }

    delete a;
}

Using pointer dereferencing.

std::cout << *(*(a->p + i) + j) << '\n';

But still requires double loop.

Inside a single loop

std::cout << *(*(a->p + (i / a->size)) + (i % a->size)) << '\n';

Upvotes: 2

Related Questions