What is the difference between these two pointer assignments in C?
Firstly, one thing common with both is that neither is an assignment.
int *p = arr[0]; // pointer points to the first element in the array
The comment here is wrong. arr
is an array of int
. arr[0]
is the first element of that array. It is an int
. int *p = arr[0]
is an attempt at initialising a pointer with the value that is stored in the array. However, the type doesn't match since the value is not a pointer. int
is not implicitly convertible to int*
and therefore the program is ill-formed.
A standard conforming language implementation is required to diagnose this issue for you. This is what my compiler says:
error: invalid conversion from 'int' to 'int*'
Why is case 1 erroring?
If the program even compiles, you are initialising a pointer with the value 0. This likely means that it is a null pointer and that it doesn't point to any object. ++*p
attempts to indirect through this null pointer and access the non-existing integer.
int *p = arr; // pointer points to the first element in the array
Comment here is correct.