Well, I unfortunately was unable to understand what exactly you are desiring to have, but I do have a vague guess about what you want from the upper half of your question, so here's what I've understood:
- You have an array of
float
values that are to be interpreted asreal
andimag
parts of theCOMPLEX
data type. 2n - 1
'th element of the array is to be interpreted as thereal
part of then
'th element, and2n
'th element is to be interpreted as theimag
part.Now this will be an assumption: You want to access them in some desirable fashion.
If I am right about those, you can achieve that by using pointers in a smart fashion. With the declaration/initialization of float x[2n]
, you have the following in your hands:
float x[10] = { 1.0, 1.5, 2.0, 2.5, 3.0, ... } //changed numbers for better distinction
Inside memory, you have the following for the thing above:
1.0 1.5 2.0 2.5 3.0 ...
//addresses or memory locations of which are:
x x+1 x+2 x+3 x+4 ...
Now, by simply making the assignment complexpair * x_ptr = x;
during initialization, or x_ptr = x;
afterwards, you make the same memory locations to be accessible with following:
x_ptr x_ptr+1 x_ptr+2 ...
And that's all! You now have an easy method to access all that, simply with these two lines:
...
float x[10] = { 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5 };
complexpair *x_ptr = x;
...
To access the real
and imag
parts of the COMPLEX
es with this, you can simply write:
x_ptr[0].cart.real; //is 1.0
x_ptr[0].cart.imag; //is 1.5
x_ptr[2].cart.imag; //is 3.5
x_ptr[4].numbers[0]; //is 5.0
...
For the reference, here's the whole code I have here that I've used for behavioural examination:
#include <stdio.h>
typedef struct cmpx {
float real;
float imag;
} COMPLEX;
typedef union complexdata {
float numbers[2];
COMPLEX cart;
} complexpair;
int main( ) {
float x[10] = { 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5 };
complexpair *x_ptr = x;
for ( int i = 0; i < 5; i++ )
printf( "%f %f\n", x_ptr[i].cart.real, x_ptr[i].cart.imag );
putchar( 10 );
for ( int i = 0; i < 5; i++ )
printf( "%f %f\n", x_ptr[i].numbers[0], x_ptr[i].numbers[1] );
getchar( );
return 0;
}