This question already has an answer here:
- Array increment operator in C 7 answers
#include <stdio.h>
int main(){
int arr[] = {1, 2, 3, 4};
int *p;
p = arr;
printf("%d\n", *p);
printf("%d\n", *arr);
p++;
printf("%d\n", *p);
}
This code outputs:
1
1
2
but when we add 2 lines as below:
#include <stdio.h>
int main(){
int arr[] = {1, 2, 3, 4};
int *p;
p = arr;
printf("%d\n", *p);
printf("%d\n", *arr);
p++;
printf("%d\n", *p);
arr++;
printf("%d\n", *arr);
}
This code outputs:
C:\Users\Hasnat\Desktop\test.c||In function 'main':|
C:\Users\Hasnat\Desktop\test.c|11|error: lvalue required as increment operand
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===
Why can not we increment an array in same way we increment pointer containing address of that array to get next element??
Because C doesn't allow assigning to array. Arrays in expressions are automatically converted to a pointer pointing at the first element of the array unless they are used for the operand of
sizeof
operating or unary&
(address) operator. (N1256 6.3.2.1)As the error message shows, the operand
arr
is converted to a pointer pointing the first element of the array and the pointer isn't a lvalue, so it cannot be modified via increment operator.To quote
C11
, chapter 6.5.2.4, Postfix increment and decrement operatorsand the definition of modifiable lvalue is given in chapter 6.3.2.1 of the same standard, Lvalues, arrays, and function designators
So, you cannot use
++
on an array. Simple.