How it works...

When you define a variable of the type structure, that variable can access members of the structure in the following format:

structurevariable.structuremember

You can see a period (.) between the structure variable and the structure member. This period (.) is also known as a dot operator, or member access operator. The following example will make it clearer:

struct cart mycart;
mycart.orderno

In the preceding code, you can see that mycart is defined as a structure variable of the cart structure. Now, the mycart structure variable can access the orderno member by making the member access operator (.).

You can also define a pointer to a structure. The following statement defines ptrcart as a pointer to the cart structure.

struct cart *ptrcart;

When the pointer to a structure points to a structure variable, it can access the structure members of the structure variable. In the following statement, the pointer to the ptrcart structure points at the address of the mycart structure variable:

ptrcart = &mycart;

Now, ptrcart can access the structure members, but instead of the dot operator (.), the arrow operator (->) will be used. The following statement accesses the orderno member of the structure using the pointer to a structure:

ptrcart->orderno

If you don’t want a pointer to a structure to point at the structure variable, then memory needs to be allocated for a pointer to a structure to access structure members. The following statement defines a pointer to a structure by allocating memory for it:

ptrcust=(struct cart *)malloc(sizeof(struct cart));

The preceding code allocates memory equal to the size of a cart structure, typecasts that memory to be used by a pointer to a cart structure, and assigns that allocated memory to ptrcust. In other words, ptrcust is defined as a pointer to a structure, and it does not need to point to any structure variable, but can directly access the structure members.

Let's use GCC to compile the pointertostruct.c program as follows:

D:\CBook>gcc pointertostruct.c -o pointertostruct

If you get no errors or warnings, that means that the pointertostruct.c program has been compiled into an executable file, pointertostruct.exe. Let's run this executable file as follows:

D:\CBook>./pointertostruct
Enter order number: 1001
Enter email address: bmharwani@yahoo.com
Enter password: gold

Details of the customer are as follows:
Order number : 1001
Email address : bmharwani@yahoo.com
Password : gold

Enter new email address: harwanibm@gmail.com
Enter new password: diamond

Modified customer's information is:
Order number: 1001
Email address: harwanibm@gmail.com
Password: diamond

Enter information of another customer:
Enter order number: 1002
Enter email address: bintu@yahoo.com
Enter password: platinum

Details of the second customer are as follows:
Order number : 1002
Email address : bintu@yahoo.com
Password : platinum


Voilà! We've successfully accessed a structure using a pointer.