Can I assign void* pointer to char* pointer?

9.3k Views Asked by At

I am coding for re-implementing malloc function. I saw a man's example code , which has some strange code like this

struct s_block{
   size_t size;    // size per block
   int free;       // whether free flag exist
   t_block pre;
   t_block next;
   void *magic_ptr;
   int padding;    // bytes for padding
   char data[1];   // first byte of data, i.e. the address returned from malloc
};

typedef struct s_block *t_block;
t_block get_block(void *p) {
   char *tmp;  
   tmp = p;
   ...
}

but I use gcc or g++ to compile this code, the error is "can't use void* pointer to char* pointer". I want to know where the question arise? gcc or g++ ? code is error?

3

There are 3 best solutions below

0
On BEST ANSWER

You have to use explicit cast to cast void* to any other pointer whereas other way is implicit.

char* temp = static_cast<char*> (p);

One thing to note here is your initial pointer ( which currently is represented by void* ) should be of type char* to avoid any issues.

0
On

In C++ you must explicitly cast a void* to another type:

char *tmp = static_cast<char*>(p);

In C this isn't the case and you can assign a void* to any pointer type without casting.

0
On

That is valid C code, the error you're getting is from the (more strict) C++ standard. If you want to compile that in C++, simply cast the pointer to char * explicitly.