Inspect the following incomplete program:
#include <stdio.h> #include <stdlib.h> /* Practice with various ways to declare things */ typedef struct { int x, y; } Point; void printPoint( Point *p ) { printf("(%d, %d) ", p->x, p->y ); } typedef struct { int red, green, blue; } Color; void printColor( Color *c ) { printf("%3d red, %3d grn, %3d blu", c->red, c->green, c->blue ); } typedef struct { Point p0, p1, p2; Color color; } Triangle; void printTriangle( Triangle *t ) { printf("Points: "); printPoint( &t->p0 ); printPoint( &t->p1 ); printPoint( &t->p2 ); printf("\nColor: "); printColor( &t->color ); printf("\n"); } int main () { /* Declare a variable here: variable directly contains a Triangle */ ???? /* Leave the following unchanged */ tri.p0.x = 15; tri.p0.y = 15; tri.p1.x = 85; tri.p1.y = 110; tri.p2.x = 50; tri.p2.y = 50; tri.color.red = 123; tri.color.green = 50; tri.color.blue = 150; /* Insert the parameter in the function call */ printTriangle( ??? ); }
Notice how the parameter t
in printTriangle()
is used.
It is a pointer to a Triangle
:
void printTriangle( Triangle *t )
Accessing a member Point
of the pointed-at Triangle
is done through the pointer t
:
t->p0
The function printPoint(Point *p)
expects a pointer to a Point
,
so the address of the Point
is supplied:
&( t->p0 )
Because of operator precedence, parentheses are not needed:
printPoint( &t->p0 );
The address-of operator &
has lower precedence
than the structure pointer member operator ->
.
Another way to do the same thing is:
printPoint( &( (*t).p0 ) );
The Puzzle: Edit main()
in the following so that it
contains the variable tri
which works correctly with the rest of the program.