Friday, October 1, 2010

Passing Structure Members to Functions in C,C++

When you pass a member of a structure to a function, you are actually passing
the value of that member to the function. Therefore, you are passing a simple
variable (unless, of course, that element is compound, such as an array). For
example, consider this structure:
struct fred
{
char x;
int y;
float z;
char s[10];
} mike;
Here are examples of each member being passed to a function:
func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */
If you wish to pass the address of an individual structure member, put the & operator
before the structure name. For example, to pass the address of the members of the
structure mike, write
func(&mike.x); /* passes address of character x */
func2(&mike.y); /* passes address of integer y */
func3(&mike.z); /* passes address of float z */
func4(mike.s); /* passes address of string s */
func(&mike.s[2]); /* passes address of character s[2] */
Remember that the & operator precedes the structure name, not the individual
member name. Note also that s already signifies an address, so no & is required.

No comments:

Post a Comment