Kunal Bisht
Kunal Bisht

Reputation: 1

comparison of two pointer variable

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

Answers (7)

Azodious
Azodious

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.

enter image description here

Upvotes: 3

jellier
jellier

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

dead programmer
dead programmer

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

Tio Pepe
Tio Pepe

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

unwind
unwind

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

Ancaron
Ancaron

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

Tudor
Tudor

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

Related Questions