C pointer to array/array of pointers disambiguation

前端 未结 13 1344
我寻月下人不归
我寻月下人不归 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:58
    int *a[4]; // Array of 4 pointers to int
    
    int (*a)[4]; //a is a pointer to an integer array of size 4
    
    int (*a[8])[5]; //a is an array of pointers to integer array of size 5 
    
    0 讨论(0)
  • 2020-11-21 06:00
    typedef int (*PointerToIntArray)[];
    typedef int *ArrayOfIntPointers[];
    
    0 讨论(0)
  • 2020-11-21 06:06

    In pointer to an integer if pointer is incremented then it goes next integer.

    in array of pointer if pointer is incremented it jumps to next array

    0 讨论(0)
  • 2020-11-21 06:07

    I don't know if it has an official name, but I call it the Right-Left Thingy(TM).

    Start at the variable, then go right, and left, and right...and so on.

    int* arr1[8];
    

    arr1 is an array of 8 pointers to integers.

    int (*arr2)[8];
    

    arr2 is a pointer (the parenthesis block the right-left) to an array of 8 integers.

    int *(arr3[8]);
    

    arr3 is an array of 8 pointers to integers.

    This should help you out with complex declarations.

    0 讨论(0)
  • 2020-11-21 06:07
    int *arr1[5]
    

    In this declaration, arr1 is an array of 5 pointers to integers. Reason: Square brackets have higher precedence over * (dereferncing operator). And in this type, number of rows are fixed (5 here), but number of columns is variable.

    int (*arr2)[5]
    

    In this declaration, arr2 is a pointer to an integer array of 5 elements. Reason: Here, () brackets have higher precedence than []. And in this type, number of rows is variable, but the number of columns is fixed (5 here).

    0 讨论(0)
  • 2020-11-21 06:10

    I guess the second declaration is confusing to many. Here's an easy way to understand it.

    Lets have an array of integers, i.e. int B[8].

    Let's also have a variable A which points to B. Now, value at A is B, i.e. (*A) == B. Hence A points to an array of integers. In your question, arr is similar to A.

    Similarly, in int* (*C) [8], C is a pointer to an array of pointers to integer.

    0 讨论(0)
提交回复
热议问题