Reputation:
I read this from a book: for double beans[3][4]
if we want to make a pointer called it pbeans
to point to it we need to declare it as
double (*pbeans) [4] =beans;
My question is:
Why it is:
double (*pbeans) [4] =beans
;
but not:
double[4] *pbeans =beans
; ?
And how should I read double (*pbeans) [4]
?
(say, const int * const pi
we can read from right to left const pointer to integer constant).
Upvotes: 0
Views: 57
Reputation: 106122
why it is
double (*pbeans) [4] =beans;
but notdouble[4] *pbeans =beans;
?
This is because you need pointer to the first element of array beans
and the first element of it is an 1D array of 4 elements.
Why not double[4] *pbeans =beans;
?
Because this is not a valid C syntax.
And how should I read
double (*pbeans) [4]
? (say,const int * const pi
we can read from right to left const pointer to integer constant).
You can read this as *pbeans
is a pointer to an array of 4
doubles
s. You can use spiral rule to parse such declarations.
Upvotes: 0
Reputation: 123598
C declaration syntax is based on the types of expressions, not objects. This is also phrased as "declaration mimics use."
You have a pointer to a 4-element array of double
named pbeans
. To access an element from the pointed-to array, you must first dereference pbeans
using the unary *
operator, and then apply the subscript to the result of that dereference:
double x = (*pbeans)[i];
The parentheses are necessary because the subscript operator []
has higher precedence than unary *
operator; if you wrote *pbeans[i]
, it would be parsed as *(pbeans[i])
, which would attempt to dereference the result of pbeans[i]
, which is not what we want.
The type of the expression (*pbeans)[i]
is double
, so it follows that the declaration of pbeans
is
double (*pbeans)[4];
The decalration is read as
pbeans -- pbeans
(*pbeans) -- is a pointer to
(*pbeans)[4] -- a 4-element array
double (*pbeans)[4]; -- of double.
Upvotes: 1
Reputation: 3162
1) It is the format in C to declare arrays using,
datatype name[][];
format. here
double (*pbeans) [4] =beans;
means pbeans
is a array of 4 items and where each item is of type double *
i.e. a pointer to double.
2)you read
const int * const pi
from right to left as pi is a constant pointer to a integer constant
Upvotes: 0