C pointer to array/array of pointers disambiguation

前端 未结 13 1743
我寻月下人不归
我寻月下人不归 2020-11-21 05:19

What is the difference between the following declarations:

int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);

What is the general rule for under

13条回答
  •  清歌不尽
    2020-11-21 05:54

    Here's how I interpret it:

    int *something[n];
    

    Note on precedence: array subscript operator ([]) has higher priority than dereference operator (*).

    So, here we will apply the [] before *, making the statement equivalent to:

    int *(something[i]);
    

    Note on how a declaration makes sense: int num means num is an int, int *ptr or int (*ptr) means, (value at ptr) is an int, which makes ptr a pointer to int.

    This can be read as, (value of the (value at ith index of the something)) is an integer. So, (value at the ith index of something) is an (integer pointer), which makes the something an array of integer pointers.

    In the second one,

    int (*something)[n];
    

    To make sense out of this statement, you must be familiar with this fact:

    Note on pointer representation of array: somethingElse[i] is equivalent to *(somethingElse + i)

    So, replacing somethingElse with (*something), we get *(*something + i), which is an integer as per declaration. So, (*something) given us an array, which makes something equivalent to (pointer to an array).

提交回复
热议问题