Domanda

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;
}
È stato utile?

Soluzione

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.

Altri suggerimenti

Yes, this is 100% legal: C standard specifies that the pointer to a struct must always equal to the pointer to the initial member of that struct.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top