char arr[] = "Hello"; arr = arr + 1; // error occurs
As far as I know, an expression that has array type is converted to pointer type that points to the initial element of the array. Therefore, I expected arr = arr + 1
(pointer to first element(arr) of the array becomes the pointer to the second element of the array)to work. Why doesn't this work in C?
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer.
Pointer multiplication, division, and addition are not permitted because they do not make sense in pointer arithmetic. In Python, there are seven arithmetic operators: addition, subtraction, multiplication, division, and modulus, Exponentiation.
Since void is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation. Therefore you cannot perform pointer arithmetic on a void pointer.
There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A list of such operations is given below. Address + Address = illegal.
arr + 1
is indeed a pointer to the second element of the array (i.e. &arr[1]
).
However, that does not mean that you can somehow write that pointer value back into arr
. You can't do it for at least two reasons.
Firstly, arr
is an array of char
elements, not a pointer. There's an obvious type mismatch here.
Secondly, being an array, arr
a non-modifiable lvalue. You cannot change arr
itself, you can only change its elements (this distinction is somewhat hard to grasp, but it is there).
Finally, if we just ignore the deeper intricacies and focus on what formally happens at the top level, due to array type decay your expression is equivalent to
(char *) arr = (char *) arr + 1;
The assignment is impossible since the left-hand side is a result of [implicit] type conversion. In C type conversions always produce rvalues. You cannot assign to rvalues.
In other words, it is not the "pointer arithmetic" that's disallowed here. The pointer arithmetic is fine. It is what you do with the result of that pointer arithmetic that causes the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With