0

I have a pointer problem which I don't understand, I hope you can help me.

int main()
{
    int tab[] = {1,2,3};
    int *ptr;
    ptr=tab; // this is where my doubt lies
    cout << &ptr << "," << ptr << "," << *ptr << "," << &tab << "," << tab << "," << *tab << endl;
    return(0);
}

to put the pointer pointing to what you want shouldn't you do, for example ptr=&something ?? If someone could explain it to me I appreciated. Thanks

Marco A.
  • 43,032
  • 26
  • 132
  • 246
Ackerman
  • 19
  • 6

3 Answers3

3

Arrays can decay into pointers to their first element, so when you do this:

ptr=tab;

tab in the RHS decays to an int* pointing to the first element of array tab. So ptr now points to that element.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

C arrays decay into pointers whenever they can. With the line

ptr=tab;

you might encounter similar behavior to

ptr=&tab;

but the types are different: in the first case you're asking for an int pointer, in the latter you're asking for a pointer to an array of ints with a specific type.

Marco A.
  • 43,032
  • 26
  • 132
  • 246
2

In C (i think maybe the same applies to C++) when an array name is used by itself, in most circumstances (*) it gets converted to a pointer to its first element.

The two lines below are effectively the same; the first has an implicit conversion

ptr = tab;
ptr = &(tab[0]);

(*) the exceptions to this rule are when the array is used as operand to the sizeof operator (sizeof tab) or "address of" operator (&tab)

pmg
  • 106,608
  • 13
  • 126
  • 198
  • The second one has an implicit conversion too, because the subscript operator is defined in terms of pointer arithmetic. So `ptr = &(tab[0]);` is precisely equivalent to `ptr = &(*(tab + 0));`, where `tab` again decays into a pointer before `0` is added to this pointer... Of course, that last form is precisely equivalent to `ptr = tab + 0;`, which is again precisely equivalent to `ptr = tab;`... – cmaster - reinstate monica Mar 30 '14 at 10:27