-5

I am studying C++ and came across this Code

    int a[] = {9,8,−5}; 
    int∗ p = &a[2] ;

and was wondering what exactly that means? So a is an Array and p is a pointer. But what does the & before a[] mean?

and what does mean then?

   std::cout << (p − a) << "\n";

edit:

so i have read some answeres but what i still dont understand is what the & is really for. Is there a difference between

  int∗ p = &a[2] ;

and

  int∗ p = a[2] ;

?

Thanks for your help.

Gregor Hohl
  • 25
  • 1
  • 6

2 Answers2

1

This code

int∗ p = &a[2];

is equivalent to this:

int∗ p = a + 2;

so even mathematically you can see that p - a is equal to a + 2 - a so I think result should be obvious that it is equal to 2.

Note name of array can decay to a pointer to the first element but is not that pointer, as many may mistakenly say so. There is significant difference.

About your note, yes there is difference, first expression assigns address of third element to p, second is syntax error as you try to assign int to int * which are different types:

int a[] = { 1, 2, 3 };
int var = a[2]; // type of a[2] is int and value is 3
int *pointer = &a[2]; // type of &a[2] is int * and value is address of element that holds value 3

Subject of your question says that you think & means reference in this context. It only means reference when applied to types, when used in expression it means different things:

int i, j;
int &r = i; // refence when applied to types
&i; // address of in this context
i&j; // binary AND in this
Slava
  • 43,454
  • 1
  • 47
  • 90
0

In your case & is used to get the address to a value. So what will happen there is that p will contain the address of a[2], thus p will be a pointer to the third element of the array.

EDIT: Demo (with p-a included)

J.Baoby
  • 2,167
  • 2
  • 11
  • 17
  • ok thanks so what does std::cout << (p − a) << "\n"; mean then? – Gregor Hohl Dec 29 '16 at 12:49
  • As `p` and `a` are both `int` pointers (an array is **almost equivalent** to a pointer to the first element), `p-a` will return how many `int` can be placed between the addresses `p` and `a` point to in memory. `a` points to the (beginning of the) first integer and `p` to (the beginning of) the third, `p-a` will then return 2. Effectively, between address `a` and address `p` there is the integer pointed to by `a` (i.e a[0]), and the integer `a[1]`. – J.Baoby Dec 29 '16 at 15:40