Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert void pointer to char pointer in C

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

like image 229
Jimmy Avatar asked Aug 15 '11 16:08

Jimmy


People also ask

Can you cast void * to char *?

void* to char**You can't. You need reinterpret_cast. You have a 'pointer to anything' and have decided to treat it as a 'pointer to a char*'. That is 'reinterpreting' the type of the memory without applying any conversions.

How do I cast a void pointer to a char array?

Simply doing array = ptr; or char * array = ptr; would perfectly do. C "implicitly converts" to/from void -pointers.

Can we typecast void pointer into in pointer?

A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.

How do I cast a void pointer to integer?

After declaration, we store the address of variable 'data' in a void pointer variable, i.e., ptr. Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable.


2 Answers

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?

like image 21
octopusgrabbus Avatar answered Oct 21 '22 17:10

octopusgrabbus


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
like image 189
Armen Tsirunyan Avatar answered Oct 21 '22 17:10

Armen Tsirunyan