Jin Jin - 2 months ago 4x
C Question

Why isn't this pointer arithmetic allowed in C?

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?


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. Secondly, being an array, arr a non-modifiable lvalue. You cannot change arr itself.

In other words, it is not the "pointer arithmetic" that disallowed here. The pointer arithmetic is fine. It is what you do with the result of that pointer arithmetic that causes the error.