I want to know the Difference between below four terms in C/C++:
p[i]
i[p]
*(p+i)
*(i+p)
Where p is Array, i is loop current index.
I want to know the Difference between below four terms in C/C++:
p[i]
i[p]
*(p+i)
*(i+p)
Where p is Array, i is loop current index.
p[i]
is equivalent to *(p+i)
, as per the standard definition. Because addition is commutative, *(p+i)
is the same as *(i+p)
. And as per the rule previously stated, *(i+p)
is equivalent to i[p]
.
So, they are all the same.
Note that this only applies to built-in operators (i.e. operators applied to built-in types). User defined operators (both []
and +
) do not have to follow these rules.
p
. This can either be a static array or a dynamic array - in either case, p
points to the first element (0).i
as a pointer to an array and p
as an index. Mathematically, it would work out to the be the same memory location, but as written, I would be surprised if it compiles (though, it does as shown in the example - but it is still a poor way to structure code as it goes against the normal convention).You can see them all here
p[i] means you are access the i+1 th element of the array p.
*(p+i) means you are defining a pointer *p, and accessing the contents of a memory location away from p by i times the size of the data that p points to.
(Again this means the same in case of array p[i], just adding the additional meaning to this when explicitly using pointer).
Assume that p is a pointer to int and that size of int is 4 bytes, then p+i points to a memory location x +4*i. where x is the memory location pointed to by p. Hence *(p+i) is used to access the contents of that memory location.
EDIT: and i[p] and*(i+p) is the same as p[i] (as I learnt just now) :)
You declare an Array arr[n]
,
arr
--->
base address of the array and n
is the offset
.arr[n]
--->
accessing the n
th element from the array or better n
offset from the base address*(arr + n)
== *(n + arr)
adding n
offset to the base address to get the element. n[arr]
== just another way of accessing the array , "associative property"