C ++ Conceptual problem with pointers (pointers)

I have a structure that usually contains a pointer to int

. However, in some special cases it is necessary that this int pointer points to another pointer, which then points to int. Wow: I've mentioned the word pointer 5 times so far!

  • Is it possible?

I thought of it this way: instead of using a second int pointer, which is most likely not possible, since my primary int pointer can only point to an int and not another int pointer, I could make a reference like this

int intA = 1;
int intB = 2;
int& intC = intB;

int* myPointers[ 123 ];
myPointers[ 0 ] = &intA;
myPointers[ 1 ] = &intB;
myPointers[ 3 ] = &intC;

      

So the above would do what I want: The reference to intB

( intC

) behaves the same as I want (if it is modified, it also changes intB

)

  • Problem: I can't change links after installing them, right? Or is there a way?

It's okay: how do I get the value to work with *

(pointers) and **

(pointers to pointers)?

+2


a source to share


3 answers


int*

and int**

are different types, so you cannot use them like others without using potentially non-portable roles.

In the ad:

int& intC = intB;

      



The link intC

will always link to int

intB

. The binding cannot be changed.

You can use union to support a type, which can be either int*

or int**

, but you need to be sure when you read which union member is valid at any given moment.

union PIntOrPPInt
{
    int* pint;
    int** ppint;
};

int intA;
int intB;
int* pintC = &intB;

PIntOrPPInt myPointers[ 123 ];

myPointers[ 0 ].pint = &intA;
myPointers[ 1 ].pint = &intB;
myPointers[ 3 ].ppint = &pintC;

      

+2


a source


You can put a pointer to intB

both elements of the array:

myPointers[ 1 ] = &intB;
myPointers[ 3 ] = &intB;

      



Thus, both elements point to the same variable, and *myPointers[1]

will always be the same as *myPointers[3]

. Is this what you want to achieve?

0


a source


We rarely use pointers to pointers in C ++. Instead, as you suggest, we use a link to pointers. However, C ++ is a strongly typed, static language. Therefore, you need to decide at compile time what your array elements will point to.

One approach is to wrap array elements in a class:

struct P {
    P() : p(0) { }
    P(int* p) : p(p) { }
    P(int** p) : p(*p) { }
    operator int*() const { return p; }
    int *p;
};

int main(int argc, char* argv[])
{
    int *i1 = new int(5);
    int **i2 = &i1;
    int *&i3 = i1;
    P arr[4] = {i1, i2, i3, P()};
    delete i1;
    return 0;
}

      

0


a source







All Articles