Reputation: 1
I come across a program in C and see the pointer comparison program. What I didn't understand is these two statements.
j=&arr[4];
k=(arr+4);
the first statement is holding the address of the fifth element and the second statement syntax is what I saw first time. Can anybody explain me the second statement. and also after executing program j and k are equal. so they are pointing to the same location.
Upvotes: 0
Views: 587
Reputation: 13872
k=(arr+4);
means k
will point to 4 elements ahead of arr
location after it is decayed into a pointer to index 0
.
array name decays to a pointer to it's zero index. by adding 4 means it'll point to 5th element.
Upvotes: 3
Reputation: 155
It's basic pointer arithmetic. k is a pointer, arr is a pointer to the first element of the array (a pointer to arr[0]). So by adding 4 to k, you move the pointer on 4 elements. Therefore k=(arr+4) means k points to arr[4], which would be the fifth element, and the same as j.
Upvotes: -1
Reputation: 4365
Every arr[4] statement is expending to (arr+4); statement by the compiler itself.
These two are equivalent and can be use interchangeably.
Upvotes: 0
Reputation: 3089
Both are ways of getting a pointer value.
First arr[x]
returns (x+1) array contents and you can get its address with & operator.
Second is known as pointer arithmetic and returns the address of the arr pointer plus x positions, so the x+1 address.
Upvotes: -1
Reputation: 399753
This is simply pointer arithmetic, mixed with C's indexing<->pointer defererence equivalence.
The former means that the expression arr + 4
causes arr
(the name of an array) to decay into simply a pointer to the array's first argument. In other words, arr == &arr[0]
is true.
The latter is this equivalency, for any pointer a and integer i:
a[i] === *(a + i)
This means that the first expression, the assignment to j
, can be read as j = &(*(a + 4))
, which makes it (pretty) clear that it's just taking the address of the element with index 4, just as the k
line is doing.
Upvotes: 1
Reputation: 504
This code uses a simple case of pointer arithmetics. It assigns the adress of the array ( +4 adresses, so it is the 5th element) to the pointer k.
Upvotes: 0
Reputation: 62439
It's the infamous pointer arithmetic! The statement simply assigns the address of the element at the address pointed to by arr
and an offset of 4 elements to the right. arr + 4
is pointing to the address of arr[4]
.
Upvotes: 1