简体   繁体   中英

Dereferencing a pointer to a struct to access its first member

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.

是的,这是100%合法的:C标准指定指向struct的指针必须始终等于指向该struct的初始成员的指针。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM