-3

On page 106 of K&R C, in strcmp function, it takes pointers *s and *t as arguments but in the for loop, it specifies

s[i]==t[i]     

as a condition.

Just want to confirm, for arrays, as

*(s+i) and s[i] 

are synonymous, hence, can the function statement use s[i] instead of *s?

Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21
mackbox
  • 199
  • 5
  • 1
    I think you're misrepresenting the function: It doesn't take "pointers `*s` and `*t`", rather, it takes pointers `s` and `t`. – Kerrek SB Jan 29 '17 at 12:59
  • 1
    A simple search for the `[]` poerator would have answered this. Before asking a question, try to solve to yourself. And how should `*s` be the same as `s[i]` (unless `i` is zero)? – too honest for this site Jan 29 '17 at 13:00
  • 1
    Yes it's true that for any valid pointer *or array* `s` and index `i` the expression `*(s + i)` is equal to `s[i]`. That means that `*s` is equal to `s[i]` ***only*** if `i` is zero (`*s` is the same as `*(s + 0)` which is the same as `s[0]`). – Some programmer dude Jan 29 '17 at 13:00
  • 1
    Yes, *(s+i) and s[i] are equivalent. – JimD. Jan 29 '17 at 13:02
  • This is the reason why `3["abcde"]` is a valid expression which evalutes to `'d'`. – Gerhardh Jan 29 '17 at 13:06
  • 1
    To expand on the comment by @Gerhardh, now that we know that `s[i]` is equal to `*(s + i)` we need to remember that addition is [*commutative*](https://en.wikipedia.org/wiki/Commutative_property) which means that `*(s + i)` is equal to `*(i + s)` which then is equal to `i[s]`. – Some programmer dude Jan 29 '17 at 13:22
  • 1
    Possible duplicate of [Pointers - Difference between Array and Pointer](http://stackoverflow.com/questions/7725008/pointers-difference-between-array-and-pointer) – Claudio Cortese Jan 29 '17 at 13:38

1 Answers1

4

From the C Standard (6.5.2.1 Array subscripting)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Thus

a[i] is equivalent to *( a + i ) and in turn is equivalent to i[a]

For example

int a[1] = { 10 };

printf( "a[0] == *( a + 0 ) is %s\n", a[0] == *( a + 0 ) ? "true" : "false" );
printf( "a[0] == 0[a] is %s\n", a[0] == 0[a] ? "true" : "false" );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335