iwahdan
iwahdan

Reputation: 449

C , Error: Expression must be a modifiable lvalue

i have the following code:

#define NULL ((void*)0)
void* Globalptr = NULL;
void func(ptrtype* input)
{
 ((ptrtype*)Globalptr) = input;
}

I get Error on line ((ptrtype*)Globalptr) = input; says " expression must be a modifiable lvalue"

Upvotes: 4

Views: 38227

Answers (6)

bare_metal
bare_metal

Reputation: 1194

The real issue here is that the cast produces an rvalue and the left operand of the assignment operator requires a modifiable lvalue.

That is why the expression ((ptrtype*)Globalptr) is not correct and as others pointed out cast is done on the right hand side of the assignment operator.

please see the lvalue_rvalue_link for details.

Upvotes: 1

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

It would have made sense if GlobalPtr was of type "ptrtype *" and input was of type "void *" like below:

ptrtype *Globalptr = NULL;
void func(void *input)
{
  Globalptr = (ptrtype *)input;
}

In your case what you could do is to convert Globalptr from "void *" to "ptrtype *". Like others already mentioned, "NULL" should not be used in this manner.

Upvotes: 1

user3522371
user3522371

Reputation:

This always works whatever the type of the pointer is (inside a function, as yours):

Pointer_Type pointer_1 = *((Pointer_Type*) pointer_2);

Upvotes: 1

Gopi
Gopi

Reputation: 19864

Please make sure you should include header file stdlib.h to bring in NULL and also don't create NULL on your own as you have done.

#include<stdlib.h>
void* Globalptr = NULL;
void func(ptrtype* input)
{
  Globalptr = input;
}

Upvotes: 1

Chinna
Chinna

Reputation: 3992

When using void pointer, have to type cast like

Globalptr = (void *)input;

And not like

((ptrtype*)Globalptr) = input;

Upvotes: 4

user694733
user694733

Reputation: 16043

You must make the data to match the variable (lvalue), and not change the type of the variable to match the data:

Globalptr = (void*)input;

But since you can convert any data pointer to void* in C, you can simply do:

Globalptr = input;

Upvotes: 9

Related Questions