How do you convert void pointer to char pointer in C

88,108

Solution 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

Solution 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?

Share:
88,108
Jimmy
Author by

Jimmy

Updated on July 09, 2022

Comments

  • Jimmy
    Jimmy almost 2 years

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

  • Jimmy
    Jimmy almost 13 years
    I'm using g++ as the compiler and not gcc. Maybe gcc has an issue with this?
  • Jimmy
    Jimmy almost 13 years
    I'm using the g++ compiler and I've compiled the code on windows visuall c++ with no problem but with g++ i get this error
  • A P Jo
    A P Jo over 3 years
    Armen, i'm only really bothered about C, but GCC gives me a -Wincompatible-pointer-types when passing a char ** to a function which takes a void ** as an argument, so is it implicit only for single pointers ?
  • Armen Tsirunyan
    Armen Tsirunyan over 3 years
    @APJo: Of course, Look a T* can be converted to void*. If you set T as char*, you will see that char** can be converted implicitly to void*, but not to void**
  • A P Jo
    A P Jo over 3 years
    @ArmenTsirunyan I'm not clear. I need this to be a void ** ...
  • Armen Tsirunyan
    Armen Tsirunyan over 3 years
    @APJo: why do you need it to be a void** and what are you going to do with it?
  • A P Jo
    A P Jo over 3 years
    There's a int chkd_malloc (void ** assign_to, size_t bytes) that assigns *assign_to = NULL if malloc fails , apart from also returning -1 . I'm passing &my_str which would make it a double-pointer ... At the moment , am just type-casting it with (void **)