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

后端 未结 6 1566
攒了一身酷
攒了一身酷 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:07

    They don't work because they imply different element sizes. Indexing an int* increases it's address by sizeof(int), as it indexes into an array of int. Indexing an int(*)[3] increases it's address by sizeof(int) * 3, as it indexes into an array of arrays of 3 ints. Thus, even though the starting address is the same, they are very different types and imply very different pointer arithmetic. The compiler is quite correct to tell you that they are not compatible.

    0 讨论(0)
  • 2021-01-25 19:11

    In C++11 if you run this:

    #include<iostream>
    template<class T>
    void foo(T t) {
      std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
    
    int main() {
       int arr[] = {1,2,3};
       foo(arr);
       foo<decltype(arr)>(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*.

    0 讨论(0)
  • 2021-01-25 19:18

    Arrays naturally decays to pointers when passed around. You don't have to use the address-of operator.

    0 讨论(0)
  • 2021-01-25 19:27

    You have mismatching types.

    The function expects *int (pointer to an int).

    array and &array[0] is of that type, *int.

    But &array is of type int(*)[3] (pointer to an array of 3 ints).

    0 讨论(0)
  • 2021-01-25 19:29

    While the address of any aggregate (this means arrays and standard-layout classes) is guaranteed to be the same as the address of the first element, the types are different, and there is no implicit conversion.


    As an example why the different type is important and useful:

    for( int *p = array; p < (&array)[1]; ++p )
    

    iterates over all elements of array, while

    for( int *p = array; p < (&array[0])+1; ++p )
    

    only executes once.

    0 讨论(0)
  • 2021-01-25 19:31

    try this:

    void fun(int* array){} // int *array is integer pointer so it can point to int not the int pointer. 
    
    int main(){
    
    int array[]={1,2,3};
    fun(array); //remove &. now *array of pm point to array[0] i.e int.
    return 0;
    }
    
    0 讨论(0)
提交回复
热议问题