having problems understanding pointers and subscripts

closed account (E3h7X9L8)
see issue in code below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  int y= 10;
  int x[] = {42, 651, 10};
  
  pointer(&y, x);

  void pointer(int *yPtr, int *xPtr2)
{

cout << *yPtr; // shows value
cout << yPtr; // shows adress

cout << *xPtr; // shows x[0] value
cout << xPtr; // shows x[0] adress
cout << xPtr[2]; // shows xPtr[2] value ?! wut ?!
                 // wasnt supposed to show the  adress of xPtr[2]? 
                 // if i try *xPtr[2] to get the value of xPtr[2] i get errors
                 // can you guys explain me in detail how it works?


}
closed account (E0p9LyTq)
http://stackoverflow.com/questions/19441793/when-are-array-names-constants-or-pointers#19441813

http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c
closed account (E3h7X9L8)
oh god another copy pasta, dont give me links , i need explanations
It's a bit out of order, reporting someone for giving you very useful links.
closed account (E0p9LyTq)
Did you even attempt to read the information at the links? Those links EXPLAIN what you need to know. From the second link:

An array is an array and a pointer is a pointer, but in most cases array names are converted to pointers. A term often used is that they decay to pointers.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

int main()
{
    int x[] { 42, 651, 10 }; // type of 'x' is 'array of 3 int'

    int* p = x ; // implicit conversion from array to pointer.

    std::cout << p << '\n' // address of first element of 'x'
              << p+1 << '\n' // address of second element of 'x'

              << x << '\n' // address of first element of 'x' (implicit conversion from array to pointer)
              << x+1 << '\n' // address of second element of 'x' (implicit conversion from array to pointer)

              << *p << '\n' // first element of 'x'
              << *(p+0) << '\n' // same as above
              << *(p+1) << '\n' // second element of 'x'

              << p[0] << '\n' // same as *(p+0)
              << p[1] << '\n' // same as *(p+1)

              << x[0] << '\n' // same as *(x+0) same as *(p+0) (implicit conversion from array to pointer)
              << x[1] << '\n' ; // same as *(x+1) same as *(p+1) (implicit conversion from array to pointer)
}
Topic archived. No new replies allowed.