I am trying to understand the implications of the following statement in C99 (C99; ISO / IEC 9899: 1999 6.5 / 7)
The object must have a stored value, accessible only with the value of the lvalue expression, which has one of the following types 73) or 88):(other statements not related to the question are omitted)an aggregate or union type that includes one of the above types among its members (including, recursively, a subaggregate member or contains union)
The object must have a stored value, accessible only with the value of the lvalue expression, which has one of the following types 73) or 88):
(other statements not related to the question are omitted)
an aggregate or union type that includes one of the above types among its members (including, recursively, a subaggregate member or contains union)
Consider the following:
typedef struct MyComplex { float real; float imag; } MyComplex; MyComplex *carray = malloc(sizeof(*carray) * 10); float *as_floats = (float *)carray;
Is this legal since the structure MyComplexcontains a compatible type floatfor a pointer as_floats?
MyComplex
float
as_floats
What about the other way? i.e:
float *farray = malloc(sizeof(*farray) * 10); MyComplex *as_complex = (MyComplex *)farray;
, , , , - float, , , ? .
, , , . , . , .
13 6.7.2.1 ( ), №1 . !
, , . , , ( -, , ) . , .
http://port70.net/~nsz/c/c99/n1256.html#6.7.2.1
! ! - , , &(carray->real), . .
&(carray->real)
, №2 .
, # 2 - OK real. , ( ), imag.
real
imag
, , , .
. , struct , - , :
// issue 1 : problem with bitFields typedef struct MyComplex_1 { unsigned int real : 1; unsigned int imag : 2; } MyComplex_1; // issue 2 : problem with members forced alignment typedef struct MyComplex_2 { unsigned int real; unsigned int imag; } __attribute__ ((aligned (64))) MyComplex_2; // GCC compiler directive int main() { MyComplex_1 arr_1[] = {{1, 2}, {1, 2}}; MyComplex_2 arr_2[] = {{1, 2}, {1, 2}}; int i; // for bitfield issue for (i=0; i<2; i++) printf("struct (%d,%d)\n", arr_1[i].real, arr_1[i].imag); for (i=0; i<4; i++) printf("var (%d)\n", ((unsigned int*)arr_1)[i]); // for struct member forced alignement issue for (i=0; i<2; i++) printf("struct (%d,%d)\n", arr_2[i].real, arr_2[i].imag); for (i=0; i<4; i++) printf("var (%d)\n", ((unsigned int*)arr_2)[i]); return 0; }
, , - , .
, , ( ), . ( 0 <= n < 10):
/* 1 */ carray[n].real /* 2 */ asfloats[n * 2]
, float, , , - . , struct MyComplex, ( , n , ).
struct MyComplex
n
, float , , , struct, 16 , (2) ( real float *) .
struct
float *
imag: , 8- , real imag.
, . , , , , , , .