[英]How to cast a pointer to void which is nested in a struct?
This example is made up for demonstration, but I need to cast the pointer as in the example 本示例是为演示而准备的,但我需要像示例中那样强制转换指针
I am getting the following errors: 我收到以下错误:
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
The code is this: 代码是这样的:
#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;
}
The commented-out part of the code works well. 该代码的注释掉部分效果很好。 I understand that the processor can not dereference the pointer without additional variable and the compiler will create an additional variable, but I want to understand how to cast the pointer that is nested in the structure without creating an additional variable?
我知道处理器不能在没有其他变量的情况下取消对指针的引用,并且编译器将创建一个附加变量,但是我想了解如何在不创建其他变量的情况下转换嵌套在结构中的指针?
Just to make the code look more compact, I will often use a similar thing and I'd like to write it in one line without additional variables. 为了使代码看起来更紧凑,我经常会使用类似的东西,并且我希望将其写成一行而没有其他变量。
C++ variant: C ++变体:
strcpy(reinterpret_cast<struct test2 *>(p->ptr)->astr, "hello world");
Also it is worth pointing out, that strcpy
function is unsafe and should not be used. 还值得指出的是,
strcpy
函数是不安全的,不应使用。 Use strcpy_s
instead. 请改用
strcpy_s
。
You need to apply ->
to the result of the cast (notice the parentheses around the entire cast expression): 您需要将
->
应用于转换结果(注意整个转换表达式周围的括号):
strcpy(((struct test2 *)(p->ptr))->astr, "hello world");
printf("%s\n", ((struct test2 *)(p->ptr))->astr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.