H K
H K

Reputation: 11

c++, manipulating the pointer to the first element of an array

I've written a small code to quickly explain my question:

    #include<iostream>
    using namespace std;

    int main()
    { int a [10] = { 200, 60, 100, 70, 0, 0, 105, 400, 450, 30};
      int *b = &a[0];
      int *c = &a[9];
      int *d = b+9;

      cout<<&b[9]<<endl
      <<c<<endl
      <<d<<endl;
    return 0;
    }

I don't understand why I had to use the address-of operator to get the same result. More specifically, shouldn't b[9] (and not &b[9]) be equal to &a[9] and b+9? I'm confused since as b is already defined as a pointer, b[9] should also be one, and it made sense to me for it to point to the same address as b+9.

And in my example, what does b[9] actually represent?

Upvotes: 1

Views: 1832

Answers (4)

Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

  • b is int*
  • b+9 is int*
  • *(b+9) is int
  • b[9] is int (the same as above)
  • &b[9] is int*
  • *(&b[9]) is int

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308206

The array subscript operator includes a dereference, which is why you need to use the address-of operator to get a pointer again.

b[9] is the same as *(b+9) by definition.

Upvotes: 1

ouah
ouah

Reputation: 145839

b[9] is the last element of your array.

&b[9] is a pointer to this element.

b + 9 is equivalent to the &b[9] form.

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168626

b[9] is, by definition, *(b+9). That is, the array operator [] sums the index and the pointer, and then dereferences that pointer.

So:

b[9] == a[9]
b+9 ==  &(a[9])

are both true statements.

Upvotes: 2

Related Questions