difference between &array[0] and &array when passed to a C function

后端 未结 5 1391
礼貌的吻别
礼貌的吻别 2020-12-17 04:20

Is there a difference between &array[0] and &array when passed to a C Function. This array is a void* array which currently takes integer as data.

Added the

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 04:59

    Assuming array is declared

    void *array[N];
    

    then the expressions &array[0] and &array will yield the same value (the address of the first element of the array is the same as the address of the array itself), but will have different types.

    Expression        Type
    ----------        ----
        &array        void *(*)[10]  -- pointer to 10-element array of `void *`
      &array[0]       void **        -- pointer to pointer to void
    

    Your function prototype will need to match up with whichever expression you pass. If you call the function as

    func(&array);
    

    then the function prototype needs to be

    void func(void *(*arrp)[10]) {...}
    

    If you call the function as

    func(&array[0]);
    

    then the function prototype needs to be

    void func(void **arrp) {...}
    

    although in that case you should pass the size of the array as a separate parameter.

    Now, assuming array is declared

    void **array = malloc(sizeof *array * N);
    

    then the expressions &array and &array[0] will yield different values and different types.

    Expression        Type
    ----------        ----
        &array        void ***  
     &array[0]        void **   
    

    &array will give you the address of the array variable itself, which is different from the address of the heap memory that's been allocated for the array. Again, your function prototype will need to match up with the type of the expression you use.

提交回复
热议问题