【问题标题】:lvalue required as increment operator [duplicate]需要作为增量运算符的左值 [重复]
【发布时间】:2014-06-29 14:36:59
【问题描述】:

我在此代码中遇到与左值相关的错误:

#include <stdio.h>
#include<string.h>

main()
{
  int a[]={10,20,30,40,50};
  int j;
  for(j=0;j<5;j++)
  {
     printf("%d\n",a);
     a++;
  }
  return 0;
}

显示的错误是:

lvalue is required as an increment operator.

为什么会出现这个问题? 任何帮助将不胜感激。

【问题讨论】:

  • 你不想printf("%d\n",a[j])吗?
  • 您缺少数组“a[j]”的索引
  • 数组名不变。

标签: c compiler-errors lvalue


【解决方案1】:

您正在尝试增加 int[] 变量,但这种变量不支持自增运算符。

如果您尝试遍历数组,您只需将用作循环条件的变量与下标运算符一起使用:

for (int j = 0; j < 5; ++j)
  printf("%d\n",a[j]);

主要问题是++x 运算符在语义上等同于x = x + 1, x。这要求 x 是可分配的 (lvalue)(因为您为其分配了一个新值),但数组是不可分配的。

【讨论】:

    【解决方案2】:

    在这个表达式中

    a++;
    

    创建了一个int * 类型的临时对象,它指向数组a 的第一个元素。您不能增加临时对象。例如,如果你写的话也是一样的

    int x = 10;
    
    ( x + 0 )++;
    

    你可以这样写程序

    #include <stdio.h>
    
    int main()
    {
      int a[] = { 10, 20, 30, 40, 50 };
      int *p;
    
      for ( p = a; p != a + sizeof( a ) / sizeof( *a ); ++p )
      {
         printf( "%d\n", *p );
         // or printf( "%p\n", p ); depending on what you want to output
      }
    
      return 0;
    }
    

    【讨论】:

      【解决方案3】:

      虽然数组确实会衰减为指针,但数组不是指针,你不能例如增加它。

      相反,你可以让它衰减到一个指针,例如

      printf("%d\n", *(a + j));
      

      【讨论】:

      • 你为什么写*(a + j)而不是a[j]?它们完全等价;在这两种情况下,a 都会衰减。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 2011-09-07
      • 2014-04-07
      相关资源
      最近更新 更多