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

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

提交回复
热议问题