有什么方法可以在 C 中对结构指针内联执行此 "cast" 的 void ptr 吗?

Is there any way to perform this "cast" of a void ptr to a structure pointer inline in C?

请注意,以下代码是通过 void 指针访问结构的人为示例,否则毫无意义。我的问题是,是否有另一种方法可以将 void 指针转换为内联结构指针(通过使用 (CAST*) 样式语法?例如,我可以避免使用 S_TEST *tester_node_ptr = tester_node.next; 行并以某种方式直接在 printf 调用中进行转换吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Set up our data structure
typedef struct test{
    int field1;
    int field2;
    char name[50];
    void *next; // We will use this void * to refer to another struct test "node" for demo purposes
} S_TEST;



int main(void)
{
    S_TEST tester_node;
    S_TEST tester_node2;
    tester_node.field1 = 55;
    tester_node.field2 = 25;
    strcpy(tester_node.name, "First Node");
    tester_node.next = &tester_node2; // We put the addr of the second node into the void ptr
    tester_node2.field1 = 775;
    tester_node2.field2 = 678;
    strcpy(tester_node2.name, "Second Node");
    tester_node2.next = NULL; // End of list


    S_TEST *tester_node_ptr = tester_node.next;
    printf("The second node's name is: %s", tester_node_ptr->name);


    return EXIT_SUCCESS;
}

好吧,您或许应该只声明 struct test *next 而不是 void *next。但无论如何:

printf("The second node's name is: %s", ((S_TEST *)tester_node.next)->name);

是的,你可以。就这么简单

((S_TEST *)tester_node.next)->name

虽然我会说使用命名变量并依赖隐式转换更具可读性。