TechCSE: Pointers to Structures

Pointers to Structures


You can define a pointer to a structure in the same way as any pointer to any type. For example:
struct emprec *ptr

defines a pointer to an emprec. You can use a pointer to a struct in more or less the same way as any pointer but the use of qualified names makes it look slightly different For example:
(*ptr).age

is the age component of the emprec structure that ptr points at – i.e. an int. You need the brackets because ‘.’ has a higher priority than ‘*’. The use of a pointer to a struct is so common, and the pointer notation so ugly, that there is an equivalent and more elegant way of writing the same thing. You can use:
prt->age

to mean the same thing as (*ptr).age. The notation gives a clearer idea of what is going on – prt points (i.e. ->) to the structure and .age picks out which component of the structure we want. Interestingly until C++ became popular the -> notation was relatively rare and given that many C text books hardly mentioned it this confused many experienced C programmers!
There are many reasons for using a pointer to a struct but one is to make two way communication possible within functions. For example, an alternative way of writing the complex number addition function is:
void comp add(struct comp *a , struct comp *b , struct comp *c)
{
c->real=a->real+b->real;
c->imag=a->imag+b->imag;
}
In this case c is now a pointer to a comp struct and the function would be used as:
add(&x,&y,&z);

Notice that in this case the address of each of the structures is passed rather than a complete copy of the structure – hence the saving in space. Also notice that the function can now change the values of x, y and z if it wants to. It’s up to you to decide if this is a good thing or not!

No comments:

Post a Comment

Copyright © TechCSE Urang-kurai