0

I made a pointer called *p and init with arr and output the result of arr and &arr;

#include<bits/stdc++.h>
using namespace std;
int main(){
    int arr[9]={1,2,3,4,5,6,7,8,9};
    cout<<arr<<endl;
    cout<<&arr<<endl;
    int *p=arr;
    cout<<p<<endl;
}

I ran it, everything is working fine and have output likes this

0xfe0dff5d0
0xfe0dff5d0
0xfe0dff5d0

l found that cout<<arr<<endl and cout<<&arr<<endl both show the same answer as 0xfe0dff5d0

In some turotorials of C++, i noted that to use pointer to control a array should be like int *p=arr // arr refers to an array. But i found that arr and &arr gives the same output, so i began to try to use &arr to init a pointer to access to an array. And i failed with error like this:

ptr-array.cpp:9:13: error: cannot convert 'int (*)[9]' to 'int*' in initialization
    9 |     int *p2=&arr;
      |             ^~~~
      |             |
      |             int (*)[9]

I'm puzzled with why arr and &arr gives the same output, but i can't init a pointer with &arr.


In addition:

As the comment under this question, i aslo found that &arr[0] aslo can init a pointer to access a array.

In short: i'm puzzled with why i can't init a pointer with &arr but init a pointer with arr and &arr[0] though all of them direct to the same address in RAM

Danhui Xu
  • 69
  • 10
  • 1
    Can't you use &arr[0] ? Calling &arr seems wrong since the array is already a pointer. Cout is probably just fixing stuff for you when you passed &arr. – Adriel Jr Jan 29 '23 at 03:40
  • @Adriel Jr Thanks for reply, you suggetions works well, but i just what to know why `arr`, `&arr`, `&arr[0] (as you comment)` all of them direct to the same RAM address, but i can't init the pointer with `&arr` and others can. – Danhui Xu Jan 29 '23 at 03:46
  • 6
    `arr` and `&arr` might have the same value, but the _types_ are different. The error you see is the type mismatch error. – tromgy Jan 29 '23 at 03:47
  • 1
    `#include` - please don't do this. See https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – Kitswas Jan 29 '23 at 03:47
  • 4
    @AdrielJr An array is not a pointer. That's just an unfortunate illusion. – aschepler Jan 29 '23 at 03:49
  • 2
    `&arr` and `&arr[0]` have the same value (in the sense that converting them to `void *` which is what happens when you stream them to `cout`) but they have different *type* - `&arr` has type `int (*)[9]` i.e. it is a pointer to an array of 9 elements, while `&arr[0]` is of type `int *`. To initialise an `int *`, the initialiser must be either of type `int *` or *implicitly convertible* to an `int *`. `arr` (the name of the array) CAN be implicitly converted to an `int *`, equal to `&arr[0]` (the "array to pointer conversion") but `&arr` (of type `int (*)[9]`) cannot be. – Peter Jan 29 '23 at 03:51

0 Answers0