Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this pointer arithmetic allowed in C? [duplicate]

Tags:

arrays

c

pointers

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?

like image 303
Jin Avatar asked Aug 09 '16 04:08

Jin


People also ask

Why arithmetic operators are not used with pointers?

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.

Which arithmetic operations are not allowed on pointers?

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.

Why can't I perform arithmetic on void * pointer?

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.

What is illegal pointer arithmetic C?

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.


1 Answers

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.

like image 164
AnT Avatar answered Oct 17 '22 13:10

AnT