使用C时,左值作为赋值错误的左操作数

Kis*_*mar 1 c pointers lvalue required

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p +1=p;/*compiler shows error saying 
            lvalue required as left 
             operand of assignment*/
   cout<<p 1;
   getch();
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 18

当在语句中有赋值运算符时,运算符的LHS必须是语言称为左值的东西.如果操作员的LHS未评估为左值,则无法将RHS的值分配给LHS.

你不能使用:

10 = 20;
Run Code Online (Sandbox Code Playgroud)

因为10不评估左值.

您可以使用:

int i;
i = 20;
Run Code Online (Sandbox Code Playgroud)

因为i它评估为左值.

你不能使用:

int i;
i + 1 = 20;
Run Code Online (Sandbox Code Playgroud)

因为i + 1不评估左值.

在您的情况下,p + 1不评估为左值.因此,你不能使用

p + 1 = p;
Run Code Online (Sandbox Code Playgroud)


dbu*_*ush 5

简而言之,左值是可以出现在赋值左侧的东西,通常是变量或数组元素。

因此,如果您定义int *p,则p是一个左值。 p+1是一个有效的表达式,但不是左值。

如果您尝试将 1 添加到p,则正确的语法是:

p = p + 1;
Run Code Online (Sandbox Code Playgroud)