Structure and Pointers
Pointers cannot hold the address of primitive types but also
can hold the address of user-defined types such as structures. The address of
the structure can be accessed in the same manner as that of other address,
using (&) ampersand operator. In order to understand this, let us consider
the following structure.
struct date
{
int dd;
int mm;
int yy;
}day, *p;
…………..
p= &date;
In the above example, a variable day is declared as a date type
variable which contains dd, mm and yy as its members. We have also declared a
pointer variable p which points to a
structure date. In other words, p is a pointer variable which will
contains the address of some date type
variable.
The statement,
p = &day;
assign the address of variable day which of type date to
pointer variable p.
Since all the members of structure are stored in contiguous
memory locations, so using p we can
access each of its member. Thus to access a single member of a structure, we
use *p followed by a dot operator which is then followed by member name. So it
is Syntax would be:
*p.member /* wrong */
but as dot operator has precedence over indirection operator
so we should parenthesize the above expression to give precedence to the above
expression to give precedence to indirection operator. It will now look like
(*p).member
For example : To
access mm member of the variable day of date we shall write
(*p).mm
Similarly we can access other member as
(*p).dd
(*p).yy
An alternative to this operator is - >. The - > is a
special operator used to access a structure member through a pointer variable.
An individual structure member can be accessed by writing
ptr - > member
Here ptr is
structure type pointer variable. In our example, the mm member can be accessed by writing.
p - >mm
Post a Comment