typedef struct { char name[NAME_LEN]; int id; int term_hours, cum_hours; int term_gp, cum_gp; } Student; Student grace; strcpy(grace.name, "Grace Hopper"); grace.id = 101; grace.term_hours = 14; ...Assuming "..." is the right code, get
grace | ||||||||
|
|
Student *new = malloc(sizeof(Student)); new->term_gp = new->cum_gp = 0.0; strcpy(new->name, "Help?");
void print_gpa(Student stu) { printf("%.4g", stu.cum_gp / stu.cum_hours); }
print_gpa(grace); print_gpa(*new);
void print_gpa(const Student *stu) { printf("%.4g", stu->cum_gp / stu->cum_hours); }
print_gpa(&grace); print_gpa(new);
typedef struct { int x, y; } Point; typedef struct { Point a, b; } Line;
Line image[MAXLINES];
printf("%d", image[9].a.x);
void DrawImage(const Line image[], int numLines) { for(int i = 0; i < numLines; i++) { MoveTo(image[i].a.x, image[i].a.y); LineTo(image[i].b.x, image[i].b.y); } }
union Message { char text[1000]; float xs[200]; } msg; strcpy(msg.text, "Hello, World"); msg.xs[0] = 3243.5234e12; msg.xs[1] = -1e5; printf("%s", msg.text);
struct Message { enum { TEXT, DATA } message_type; union MessageContents { char text[1000]; float xs[200]; } contents; } msg; ... if ( msg.message_type == TEXT ) display(msg.contents.text); else print_table(msg.contents.xs);
typedef long my_type; long a = 5; my_type b = a; // ok!
typedef meters double; typedef kilograms double; meters m; ... kilograms k = m; // legal
struct Stack { int data[100]; int count; }; struct Set { int data[100]; int count; }; ... struct Stack a, b; ... a = b; // ok! ... struct Set x; x = a; // illegal!
typdef struct { int data[100]; int count; } Stack100;creates an anonymous struct that's distinct from Set, Stack.