这个示例是为了演示而编写的,但我需要像示例中那样转换指针
我收到以下错误:
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/