![](/img/trans.png)
[英]How to cast a C void* pointer to a pointer to a struct (with definition of the struct as a string)?
[英]How to cast a pointer to void which is nested in a struct?
本示例是为演示而准备的,但我需要像示例中那样强制转换指针
我收到以下错误:
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
。
您需要将->
应用于转换结果(注意整个转换表达式周围的括号):
strcpy(((struct test2 *)(p->ptr))->astr, "hello world");
printf("%s\n", ((struct test2 *)(p->ptr))->astr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.