【发布时间】:2013-09-05 16:41:50
【问题描述】:
出于特定原因,我只想通过取消引用指向结构的指针来访问结构的第一个成员。
我想知道这是否合法或在某些情况下会导致 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;
}
【问题讨论】:
-
为什么不直接使用 void **v = &t->data ?
-
@giorashc 对 t 的标识在我的代码中丢失了,我只有一个指向 t 的空指针。以上只是一个例子。
标签: c pointers struct dereference