A
It's all very simple to do a set of structural and cell shifts. Then all fields can be indexed. The example fills the structure using the cycle.// gcc -Wall -Wextra -Wpedantic -std=c11 offset2.c -o offset2
# include <stddef.h>
# include <stdio.h>
# include <stdint.h>
# include <stdlib.h>
typedef
struct s_S {
int i [ 6 ] ;
char c [ 6 ] ;
} S ;
define indexSize 12
int indexS [ indexSize ] = {
offsetof ( S , i [ 0 ] ) ,
offsetof ( S , i [ 1 ] ) ,
offsetof ( S , i [ 2 ] ) ,
offsetof ( S , i [ 3 ] ) ,
offsetof ( S , i [ 4 ] ) ,
offsetof ( S , i [ 5 ] ) ,
offsetof ( S , c [ 0 ] ) ,
offsetof ( S , c [ 1 ] ) ,
offsetof ( S , c [ 2 ] ) ,
offsetof ( S , c [ 3 ] ) ,
offsetof ( S , c [ 4 ] ) ,
offsetof ( S , c [ 5 ] )
} ;
enum { typeSInt , typeSChar } ;
int typeS [ indexSize ] = {
typeSInt , typeSInt , typeSInt ,
typeSInt , typeSInt , typeSInt ,
typeSChar , typeSChar , typeSChar ,
typeSChar , typeSChar , typeSChar
} ;
int main ( ) {
volatile S s ;
int i ;
for ( i = 0 ; i < indexSize ; ++ i )
switch ( typeS [ i ] ) {
case typeSInt :
* ( volatile int * ) ( ( ( uint8_t * ) & s ) + indexS [ i ] ) = 0 ;
break ;
case typeSChar :
* ( volatile char * ) ( ( ( uint8_t * ) & s ) + indexS [ i ] ) = '0' ;
break ;
default :
fprintf ( stderr , "main : typeS [ %d ] = %d\n" , i , typeS [ i ] ) ;
exit ( 1 ) ; }
fprintf ( stdout ,
"s = { { %d , %d , %d , %d , %d , %d } ,\n"
" { '%c' , '%c' , '%c' , '%c' , '%c' , '%c' } }\n" ,
s . i [ 0 ] , s . i [ 1 ] , s . i [ 2 ] ,
s . i [ 3 ] , s . i [ 4 ] , s . i [ 5 ] ,
s . c [ 0 ] , s . c [ 1 ] , s . c [ 2 ] ,
s . c [ 3 ] , s . c [ 4 ] , s . c [ 5 ] ) ; }
Type volatile S s ; You need to be because you're changing the structure. Not straight, and the compiler doesn't see you altering the structure yourself.Standard :A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned69) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.== sync, corrected by elderman == @elder_manThe indicator on the type of object may be converted into an index to another type of object. If the releasing index is not level enough for the reference type, the conduct is not defined. Otherwise, if reversed, the result would be compared to the reference index. When the indicator on the object is converted to a symbolic type, the result shall indicate the lowest point addressed by the site. Consistent delivery of the result, up to the size of the facility, is provided by the indicators on the remaining site.Used offsetof receive the correct (real) levelling of the structure field.