C语言 你如何在C中将void指针转换为char指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7067927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:24:13  来源:igfitidea点击:

How do you convert void pointer to char pointer in C

cpointersvoid-pointers

提问by Jimmy

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*'

错误:从“void*”到“char*”的无效转换

回答by Armen Tsirunyan

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 implicitin C (unlike C++), that is, the following should compile as well

实际上,您的编译器一定有问题(或者您还没有讲述完整的故事)。这是完全合法的投出void*char*。此外,转换在 C 中是隐式的(与 C++ 不同),也就是说,以下内容也应该编译

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

回答by octopusgrabbus

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

我刚刚在名为 temp.c 的模块中尝试了您的代码。我添加了一个名为 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.

在 Linux 上,我输入了 gcc -c temp.c,并且编译时没有错误或警告。

On which OS are you trying this?

你在哪个操作系统上尝试这个?