2

出于特定原因,我想通过取消引用指向结构的指针来仅访问结构的第一个成员。

我想知道这是否合法或在某些情况下会导致 UB;如果这个有任何问题,什么是正确的解决方案。

谢谢你。

#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;
}
4

2 回答 2

9

是的,这是合法的。从 C99,6.7.2.1.13:

一个指向结构对象的指针,经过适当的转换,指向它的初始成员(或者如果该成员是位域,则指向它所在的单元),反之亦然。结构对象中可能有未命名的填充,但不是在其开头。

于 2013-09-02T14:35:44.420 回答
4

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

于 2013-09-02T14:31:37.513 回答