why cant we pass &array to function where &array[0] is possible

后端 未结 6 1567
攒了一身酷
攒了一身酷 2021-01-25 18:34
void fun(int* array){}  


int main(){

int array[]={1,2,3};
fun(&array);----->(1)//error in this line
return 0;
}

error: cannot convert â

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 19:11

    In C++11 if you run this:

    #include
    template
    void foo(T t) {
      std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
    
    int main() {
       int arr[] = {1,2,3};
       foo(arr);
       foo(arr);
       foo(&arr);
       foo(&arr[0]);
    }
    

    It will produce the result:

    void foo(T) [with T = int*]
    void foo(T) [with T = int [3]]
    void foo(T) [with T = int (*)[3]]
    void foo(T) [with T = int*]
    

    Interestingly, the array collapses into a pointer by default (not sure if this is gcc behaviour or expected). However, the second line shows that the type of arr is int[3], and so &arr is a pointer to int[3] which is different than int*.

提交回复
热议问题