For specific reasons i want to access only the first member of a struct by dereferencing the pointer to the struct.
I would like to know if is this legal or can it cause UB under some conditions; and what would be a correct solution, if this one has any problems.
Thank you.
#include <stdio.h>
#include <stdlib.h>
typedef struct test_s
{
void * data ;
struct test_s * next ;
} test_t ;
int main( void )
{
test_t * t = calloc( 1 , sizeof( test_t ) ) ;
int n = 123;
t->data = &n ; //int is used only for an address, this could be anything, an object for example
void ** v = ( void* )t ;
printf("Address of n: %p\nAddress of *t: %p\n\n" , &n , *v ) ; //dereference the pointer to struct to access its first member
return 0;
}
Yes, this is legal. From C99, 6.7.2.1.13:
A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.