2014-12-01 59 views
2

这个例子是由示范,但我需要转换指针作为例子如何将指针转换为嵌套在结构中的void?

我收到以下错误:

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; 
} 

代码的注释部分运行良好。我明白,处理器不能取消引用没有额外变量的指针,编译器将创建一个额外的变量,但我想了解如何投射嵌套在结构中的指针而不创建额外的变量?

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

+2

'的strcpy(((结构测试2 *)P- > ptr) - > astr,“hello world”);' – BLUEPIXY 2014-12-01 18:31:24

+0

我需要像这样转换:'p - >(struct test2 *)ptr-> astr'但是编译器得到错误 – 2014-12-01 18:31:59

+0

代码需要测试从malloc返回的值在使用之前。否则代码将取消引用地址0,这将导致seg故障事件 – user3629249 2014-12-01 18:34:08

回答

2

C++变体:

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

另外,值得指出的是,该功能strcpy是不安全的,并且不应当被使用。改为使用strcpy_s

2

您需要申请->到铸造(注意周围的整个剧组表达括号)的结果:

strcpy(((struct test2 *)(p->ptr))->astr, "hello world"); 
printf("%s\n", ((struct test2 *)(p->ptr))->astr); 

Live example