Home > Blockchain >  Initialization of an array of pointers to pointers
Initialization of an array of pointers to pointers

Time:08-16

I need to initialize an array of pointers to pointers to four variables a, b, c and d in this way:

float a = 2.8f, b = 3.7f, c = 4.6f, d = 5.5f;
float *pts[] = { &a, &b, &c, &d };
float **ptpts[4];

void main() {
    ptpts[0] = &pts[0];
    ptpts[1] = &pts[1];
    ptpts[2] = &pts[2];
    ptpts[3] = &pts[3];

    int i;
    for (i = 0; i < 4; i  ) {
        printf("ptpts[%d] = %f\n", i, **ptpts[i]);
    }
}

Isn't there a simpler way to initialize the array ptpts directly at declaration using directly the array pts in order to get rid of the assignment of each element in ptpts one by one. Something like that (but doesn't work):

float *pts[] = { &a, &b, &c, &d };
float **ptpts = &pts; // => initialization from incompatible pointer type

In other words, isn't there a way to get the corresponding array of references from an array of pointers ?

CodePudding user response:

float ..... = &pts;

Yes you can but you need another pointer type (pointer to array):

float a = 2.8f, b = 3.7f, c = 4.6f, d = 5.5f;
float *pts[] = { &a, &b, &c, &d };
float *(*ptpts)[4] = &pts;

for (size_t i = 0; i < 4; i  ) 
{
    printf("*ptpts[0][%zu] = %f\n", i, *ptpts[0][i]);
}

or

    for (size_t i = 0; i < 4; i  ) {
        printf("ptpts[%zu] = %f\n", i, *(*ptpts[i]));
    }

Yes you can even without any variables

int main(void)
{
    float **pptrs[] = {(float **){&(float *){&(float){1.0f}}}, 
                    (float **){&(float *){&(float){2.0f}}}, 
                    (float **){&(float *){&(float){3.0f}}}, 
                    (float **){&(float *){&(float){4.0f}}}, };
}

CodePudding user response:

The array can be defined and initialized inline this way:

float **ptpts[] = { &pts[0], &pts[1], &pts[2], &pts[3]};

If the array is global and the initization local in main, a loop or a series of assignments is required.

CodePudding user response:

It's okay to use whitespace to aid readability.

int main() {
    float a=2.8f, b=3.7f, c=4.6f, d=5.5f;
    float *pts[]={ &a, &b, &c, &d };

    // What you want?
    float **ptpts[] = { &pts[0],  &pts[1], &pts[2],  &pts[3] };

    for( int i = 0; i < 4; i   )
        printf("ptpts[%d] = %f\n", i, **ptpts[i]);

    return 0;
}

Output:

ptpts[0] = 2.800000
ptpts[1] = 3.700000
ptpts[2] = 4.600000
ptpts[3] = 5.500000
  • Related