简体   繁体   中英

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?

  • 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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM