How do you convert void pointer to char pointer in C

一个人想着一个人 提交于 2019-12-04 16:29:47

问题


Ok this has been become sooo confusing to me. I just don't know what is wrong with this assignment:

void *pa; void *pb;
char *ptemp; char *ptemp2; 

ptemp = (char *)pa;
ptemp2 = (char *)pb;

Can anyone tell me why I'm getting this error:

error: invalid conversion from ‘void*’ to ‘char*’


回答1:


Actually, there must be something wrong with your compiler(or you haven't told the full story). It is perfectly legal to cast a void* to char*. Furthermore, the conversion is implicit in C (unlike C++), that is, the following should compile as well

 char* pChar;
 void* pVoid;
 pChar = (char*)pVoid; //OK in both C and C++
 pChar = pVoid;        //OK in C, convertion is implicit



回答2:


I just tried your code in a module called temp.c. I added a function called f1.

void *pa; void *pb;
char *ptemp; char *ptemp2;

f1()
{
        ptemp = (char *)pa;
        ptemp2 = (char *)pb;
}

On Linux I entered gcc -c temp.c, and this compiled with no errors or warnings.

On which OS are you trying this?



来源:https://stackoverflow.com/questions/7067927/how-do-you-convert-void-pointer-to-char-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!