简体   繁体   English

取消引用指向结构的指针以访问其第一个成员

[英]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; 我想知道这是否合法,或者在某些情况下是否会导致UB; 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: 从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的初始成员的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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