gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:31:31 25 4
gpt4 key购买 nike

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

我想知道这是否合法,或者在某些情况下会导致 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;
}

最佳答案

是的,这是合法的。来自 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.

关于c - 取消引用指向结构的指针以访问其第一个成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18575471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com