Reputation: 829
What will int (*ptr)[30];
create?
In general what happens if a variable name (in this case a pointer) is in parentheses ?
Upvotes: 3
Views: 3873
Reputation: 123458
In this case, ptr
is a pointer to a 30-element array of int
.
Postfix operators such as []
have higher precedence than unary operators such as *
, so the expression *a[i]
will be parsed as *(a[i])
(a
is an array of pointer). To use a pointer to an array, you must explicitly group the unary *
operator with the array name, such as (*a)[i]
(a
is a pointer to an array).
Handy table:
*a[N] -- a is an N-element array of pointer
(*a)[N] -- a is a pointer to an N-element array
*f() -- f is a function returning a pointer
(*f)() -- f is a pointer to a function.
Upvotes: 1
Reputation: 6333
this kind of question can always be answered by looking at the expression inside-out, with precedence considered.
in your case:
int (*ptr)[30];
can be viewed as
int (*ptr)[30];
-> ptr a variable called ptr
--> *ptr which is a pointer
---> (*ptr)[30] which points to an array with length of 30
----> int (*ptr)[30] in which each element is of type int
if the parens are dropped, the story becomes:
int *ptr[30];
-> ptr a variable called ptr
--> ptr[30] which is an array with length of 30
---> *ptr[30] in which each element is a pointer
----> int *ptr[30] and each individual points to an int
the same trick can always be applied to any expression about variable declaration.(note that function declaration is special. but it still can be analyzed in such way up to a point.)
Upvotes: 4
Reputation: 4314
As explained by the other answer, it's a pointer to an array of 30 integers.
How do you actually use these kinds of declarations:
int arr[30];
int (*ptr)[30] = &arr;
(*ptr)[0] = 5;
printf("%d\n", arr[0]);
So, it's a pointer to an array of 30 elements, not pointer to the first element of the array, although their memory addresses are the same (see casting pointer to array into pointer).
Note that &arr
has a different type than arr
even though when casted into void *
they evaluate to the same addresses.
It's somewhat esoteric; you would use pointer to the first element of the array instead of pointer to the array itself most of the time.
Upvotes: 2
Reputation: 19864
int (*ptr)[30];
Here ptr is a pointer to an array of type int
with 30 elements.
So without the parantheses
int *ptr[30];
will create an array ptr
which holds 30 integer pointers.
Upvotes: 4