左值错误和数组指针

Lvalue errors and array pointers

代码是这样的

#include<stdio.h>
#include<stdlib.h>
int main()
{
 int a[]={10,20,30,40,50};
 int j;
 for(j=0;j<5;j++)
 {
  printf("%d\n",*a);
  a++;
 }
 return 0;
}

输出-

Error-:Lvalue required as increment operand

为什么这里会出现左值错误?

++ 的操作数必须是可修改的左值。

来自 C11,章节 §6.5.2.4

The operand of the postfix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.

数组名,不是可修改的左值。因此,它不能用作 ++.

的操作数

添加,引用 C11,章节 §6.3.2.1

[...] A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a constqualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a constqualified type.

您不能增加数组的名称。你会做以下事情吗,因为你会使用指针,所以会很好:

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

您可以使用在指针数组上添加索引值来显示数组值。

代码:

#include <stdio.h>

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

 return 0;
}

输出: