Mircea Ispas
Mircea Ispas

Reputation: 20790

C++ error on f(void*&) call

Can you please explain the error from following code please:

void foo(void*& param)
{
    param = new char[10];
}

void main()
{
    int* p;
    foo(p);
}

error C2664: 'foo' : cannot convert parameter 1 from 'int *' to 'void *&'

How may I call a function with any pointer type and change that pointer inside the function(not the value at that address, the address itself). I don't want to use templates or double pointers.

Upvotes: 0

Views: 197

Answers (2)

Why can you not pass an int* as argument to f?

The problem is that if that was allowed you would be breaking the type system. Which to be honest is exactly what you are trying to do... If you want to break the type system you will need to explicitly request it by means of a cast.

You point out in a comment that you don't want to use casts, on the other hand the compiler does not want you to break the type system. In that battle of wills, I don't think you are going to convince the compiler... it is just too stubborn.

Upvotes: 2

Horonchik
Horonchik

Reputation: 477

if you want to update your pointer, its better to pass a pointer to a pointer

void foo(void** param)
{
    *param = new char[10];
}

void main()
{
    void* p;
    foo(&p);
    int* p2 = (int*)p;
}

Upvotes: 2

Related Questions