CSC 357 Lecture Notes Week 2, Part 3
Details of Pointers, Arrays, and Structs, Cont'd
struct struct-tag {where struct-tag is a name, and fields are variable declarations; the tag is optional.
fields
}
struct point {
int x;
int y;
}
struct { ... } x, y, z;
is syntactically analogous to
int x, y, z;
(but a cleaner-looking form of struct naming is with typedef, as we'll see shortly).struct point pt;
struct point maxpt = {320, 200};
pt.x = 10;
pt.y = 20;
printf("%d,%d", pt.x, pt.y);
struct rect {
struct point pt1;
struct point pt2;
};
thenstruct rect screen;
refers to the x coordinate of the pt1 field.screen.pt1.x
struct point *pp;
#define MAXWORDS 100
struct { char* word; int count; } wordtab[MAXWORDS];
wordtab[i].word[j] = getchar(); /* set the jth char of the the ith word */ wordtab[i].count++; /* increment the count of the ith word */
struct wordcnt {
char* word;
int count;
};
struct wordcnt wordtab[MAXWORDS]; /* array of structs */
struct wordcnt* wordtabp[MAXWORDS]; /* array of pointers to structs */
struct tnode { /* the tree node */
char* word; /* points to the text of a word */
int count; /* number of occurrences */
struct tnode* left; /* left child */
struct tnode* right; /* right child */
};
which can be used in declarations liketypedef int Length;
Length len, maxlen; Length getLength(...);
typedef struct {
char* word;
int count;
} WordCount;
WordCount wordtab[MAXWORDS];
WordCount* wordtabp[MAXWORDS];
typedef struct tnode { /* the tree node */
char* word; /* points to the text of a word */
int cound; /* number of occurrences */
struct tnode* left; /* left child */
struct tnode* right; /* right child */
} TreeNode;
TreeNode* tree;
typedef struct tnode { /* the tree node */
char* word; /* points to the text of a word */
int cound; /* number of occurrences */
TreeNode* left; /* left child, with INVALID FORWARD REF */
TreeNode* right; /* right child, with INVALID FORWARD REF */
} TreeNode;
typedef union {
int int_val;
double double_val;
char* string_val;
unsigned char bool_val;
} GenericValue;
typedef enum {INT, DOUBLE, STRING, BOOL} ValueTag;
typedef struct {
ValueTag tag;
GenericValue val;
} TaggedGenericValue;
void PrintTaggedGenericValue(TaggedGenericValue v) {
switch (v.tag) {
case INT:
printf("%d0, v.val.int_val);
break;
case DOUBLE:
printf("%f0, v.val.double_val);
break;
case STRING:
printf("%s0, v.val.string_val);
break;
case BOOL:
printf("%s0, v.val.bool_val ? "true" : "false");
}
}
main() {
TaggedGenericValue tval;
tval.val.int_val = 10;
tval.tag = INT;
PrintTaggedGenericValue(tval);
tval.val.bool_val = 0;
tval.tag = BOOL;
PrintTaggedGenericValue(tval);
}
tells doxygen to treat a .h file similar to how javadoc treats a .java class file; this means that doxygen treats C typedefs similar to Java classes./*! \file
allows struct field comments to appear after the field decls instead of before; this is in keeping with an often-used commenting style in C./**<
www.csc.calpoly.edu/~gfisher/classes/357/examples/person-record/html/