A constructor for a TriangleMod
struct
allocates memory for the main struct and the structs
it points to (of type Point
and Color
).
Non-pointer members are initialized to zero.
Write a newTriangleMod()
function in the following:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int x, y;
} Point;
void printPoint( Point *p )
{
printf("(%d, %d) ", p->x, p->y );
}
Point *newPoint()
{
Point *p = (Point *)malloc( sizeof( Point ) );
p->x=0;
p->y=0;
return p;
}
void setPoint( Point *p, int x, int y )
{
p->x = x; p->y = y;
}
typedef struct
{
int red, green, blue;
} Color;
Color *newColor()
{
Color *c = (Color *)malloc( sizeof( Color ) );
c->red=0;
c->green=0;
c->blue=0;
return c;
}
/* function to set a Color */
void setColor( Color *c, int r, int g, int b )
{
if ( r<0 || r>255 ) r = 0;
if ( g<0 || g>255 ) g = 0;
if ( b<0 || b>255 ) b = 0;
c->red = r;
c->green = g;
c->blue = b;
}
void printColor( Color *c )
{
printf("%3d red, %3d grn, %3d blu", c->red, c->green, c->blue );
}
/* Write this function */
/* Use newColor() and newPoint() (above) */
TriangleMod *newTriangleMod()
{
}
int main()
{
TriangleMod *trimod = newTriangleMod();
/* Initialize trimod here */
/* Print out trimod here */
printTriangleMod( trimod );
/* Free memory here */
}
The next puzzle has you write a destructor for TriangleMod
.
You can write it and include it in this program if you want.