c - 如何将指针转换为嵌套在结构中的 void ?

标签 c pointers struct casting

这个示例是为了演示而编写的,但我需要像示例中那样转换指针

我收到以下错误:

test2.c: In function ‘main’:
test2.c:25:12: error: expected identifier before ‘(’ token
test2.c:25:12: error: too few arguments to function ‘strcpy’
test2.c:26:20: error: expected identifier before ‘(’ token

代码是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test {
        void *ptr;
        char str[300];
};
struct test2 {
        int i;
        char astr[200];
};

int main(void)
{
        struct test *p;
        p = malloc(sizeof(struct test));
        p->ptr = malloc(sizeof(struct test2));
        /*
        void *p2;
        p2 = p->ptr;
        strcpy(((struct test2 *)p2)->astr, "hello world");
        printf("%s\n", ((struct test2 *)p2)->astr);
        */
        strcpy(p->(struct test2 *)ptr->astr, "hello world");
        printf("%s\n", p->(struct test2 *)ptr->astr);
        return 0;
}

代码中注释掉的部分效果很好。我知道处理器无法在没有附加变量的情况下取消引用指针,并且编译器将创建一个附加变量,但我想了解如何在不创建附加变量的情况下转换嵌套在结构中的指针?

为了让代码看起来更紧凑,我会经常使用类似的东西,并且我想将其写在一行中,而不需要额外的变量。

最佳答案

C++ 变体:

strcpy(reinterpret_cast<struct test2 *>(p->ptr)->astr, "hello world");

还值得指出的是,strcpy 函数不安全,不应使用。请改用 strcpy_s

关于c - 如何将指针转换为嵌套在结构中的 void ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27234795/

相关文章:

c++ - 将结构传递给头文件中的函数

c++ - "array bound is not an integer constant"在运行时创建结构

gdb可以自动在SIGSEGV上附加一个进程吗

c++ - 命令行 XRandR 和自己的代码之间的差异

c - 当指向前一个节点的指针不可用时从单个链表中删除中间节点

c - C 中没有任何指针的无限数组索引

c - 如何打印特定三角形的数组?

c++ - 我正在尝试计算 char 数组中的内容直到空终止,但每次编译时我得到的数字都大于我的数组

c - 我想用指针将一些字符串放在动态二维数组中(C 编程)

c - 在 C90 中将位字段和其他数据类型作为单个结构中的字段是不好的做法吗?