What is the difference between the following declarations:
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
What is the general rule for under
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
typedef int (*PointerToIntArray)[];
typedef int *ArrayOfIntPointers[];
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
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.
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).
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.