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 ?
Edit:
Following some comments, I give here a piece of background to explain how I came to that question. This may help to propose the solution or give idea for a better architecture.
I have the following interface (interface.h) for the program I'm developing. Depending on a flag PTTYPE defined at compilation time, the interface will be a set of variables or a set of pointers depending on the environment where the program is deployed. The program must be compliant with both kind of interface type (PTTYPE=1 or PTTYPE=0).
// interface.h
#if PTTYPE
float *pta, *ptb, *ptc, *ptd;
#define a (*pta)
#define b (*ptb)
#define c (*ptc)
#define d (*ptd)
#else
float a, b, c, d;
#endif
I'm not the owner of this interface file and can't modify it. I must just include this file in my program and want to have a simple and unique way to reach the values. That's why I thought about using an array of pointers to pointers and would have something like that:
#include "interface.h"
#if PTTYPE
float **ptpts[]={ &pta, &ptb, &ptc, &ptd };
#else
float *pts[]={ &a, &b, &c, &d };
float **ptpts = &pts; // => initialization from incompatible pointer
#end
void main() {
a=2.8f;
b=3.7f;
c=4.6f;
d=5.5f;
int i;
for (i = 0; i < 4; i++) {
printf("ptpts[%d] = %f\n", i, **ptpts[i]);
}
}
float **ptpts[] = { &pts[0], &pts[1], &pts[2], &pts[3] };and let the compiler provide the dimension.