0

I was trying out different statements to understand how variables and pointers are stored in the memory. I came across this:

void temp(int arr[]){
    cout<<&arr<<" "<<&arr+1;
}

int main(){
    int arr[] = {1,2,3};
    cout<<arr<<" "<<arr+1<<endl;
    cout<<&arr<<" "<<&arr+1<<endl;
    temp(arr);
    return 1;
}

An output is:

0x7fff4d2fe154 0x7fff4d2fe158
0x7fff4d2fe154 0x7fff4d2fe160
0x7fff4d2fe128 0x7fff4d2fe130
  • I can't understand how arr and &arr print the same address. As per my knowledge, arr is a pointer to the first element of the array. So shouldn't &arr print the address of the pointer?

  • Reason for the third output I found online was:

    When the array arr is passed to the function it decays to a pointer

What does this mean? Wasn't arr a pointer in the first place? My understanding is probably flawed, do correct me. Thanks for reading!

  • At least one of your questions is a duplicate, and closed as such. – SergeyA Aug 04 '21 at 18:42
  • The provided answer answers the second question. Could you comment on the first part? Thanks! – Sinadin Shan Aug 04 '21 at 18:54
  • 1
    This is why you are encouraged to ask one question per question. Feel free to ask separate question to clarify other items. – SergeyA Aug 04 '21 at 18:55
  • 1
    All your questions seem to presume that `arr` in `main` is a pointer, correct? It is not a pointer. It is an array. – Drew Dormann Aug 04 '21 at 18:56
  • @SergeyA Thanks for the info, I'll keep that in mind. – Sinadin Shan Aug 04 '21 at 18:58
  • @DrewDormann How can the two `cout` statements in main be explained then..they are printing the address of the first element of the array right? I have been having the idea that array name is a pointer to the first element. – Sinadin Shan Aug 04 '21 at 19:01
  • 1
    @SinadinShan read [the duplicate](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). `&arr` is an explicit pointer to the array. `arr` is implicitly converting to a pointer to the array. It's called "array to pointer decay". – Drew Dormann Aug 04 '21 at 19:11

0 Answers0