2014-12-01 58 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