type *ptvar;
where type is a data type that identifies the composition of the structure, and ptvar represents the name of the pointer variable.The beginning address of a structure can be assigned to this pointer by writing
ptvar = &variable;
The variable declaration and pointer declaration can be combined with the structure declaration by writing
struct {
member 1;
member 2;
...............
member n;
} variable, *ptvar;
An individual member of a structure can be accessed in terms of its corresponding pointer variable by writing
ptvar->member;
which is equivalent to writing
variable.member;
The operator -> is comparable to the period operator (.).
Consider the simple C program shown below,
#include < stdio.h >
main()
{
int n=5120;
char t = 'R';
float b = 100.35;
typedef struct {
int month;
int day;
int year;
} date;
struct {
int *acct_no;
char *acct_type;
char *name;
float *balance;
date lastpayment;
} customer, *pc = &customer;
customer.acct_no = &n;
customer.acct_type = &t;
customer.name = "Smith";
customer.balance = &b;
printf("%d %c %s %.2f\n", *customer.acct_no, *customer.acct_type, customer.name, *customer.balance);
printf("%d %c %s %.2f\n", *pc->acct_no, *pc->acct_type, pc->name, pc->balance);
}
The members acct_no, acct_type, name, balance are written as pointers within the second structure.Thus, the value to which acct_no points can be accessed by writing either
*customer.acct_no or *pc->acct_no.The same way other members can also be accessed.
Execution of the program results in the following two lines of output.
5120 R Smith 100.35
5120 R Smith 100.35
These two lines of output are identical, as expected.
No comments:
Post a Comment