C语言 C,错误:表达式必须是可修改的左值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26465048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:29:34  来源:igfitidea点击:

C , Error: Expression must be a modifiable lvalue

cpointerscastingvoid-pointers

提问by Islam Wahdan

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"

我在网上收到错误消息((ptrtype*)Globalptr) = input;说“表达式必须是一个可修改的左值”

回答by user694733

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:

但是由于您可以将任何数据指针转换为void*C 语言,您可以简单地执行以下操作:

Globalptr = input;

回答by Chinna

When using void pointer, have to type cast like

使用 void 指针时,必须像这样进行类型转换

Globalptr = (void *)input;

And not like

而且不喜欢

((ptrtype*)Globalptr) = input;

回答by Gopi

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.

请确保您应该包含头文件 stdlib.h 以引入 NULL,并且不要像您所做的那样自行创建 NULL。

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

回答by Gopi

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

无论指针的类型如何,这始终有效(在函数内部,如您的那样):

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

回答by Arjun Mathew Dan

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

如果 GlobalPtr 的类型为“ptrtype *”并且输入的类型为“void *”,则如下所示:

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.

在您的情况下,您可以做的是将 Globalptr 从“void *”转换为“ptrtype *”。像其他人已经提到的那样,不应以这种方式使用“NULL”。

回答by bare_metal

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.

这就是为什么表达式 ((ptrtype*)Globalptr) 不正确,正如其他人指出的那样,强制转换是在赋值运算符的右侧完成的。

please see the lvalue_rvalue_linkfor details.

有关详细信息,请参阅lvalue_rvalue_link