// mystring.c // define and test mystring type. // Created: Thu 10 March 2005 at 12:56 UT+11. #include #include #include // Data Type mystring typedef struct {char *str; int maxlen;} mystring; // Function prototypes mystring create_string (int); void free_string (mystring); void prompt_read_string (mystring*); void read_string2 (mystring*); void use_strings (void); void write_string (mystring); void write_named_string (char name3[], mystring s7); int main (void) { use_strings(); return 0; } void use_strings (void) { mystring s1 = create_string (5); prompt_read_string (&s1); write_named_string ("s1", s1); free_string (s1); } mystring create_string (int maxsize) { mystring s0; if (maxsize <= 0) { fprintf (stderr, "create_string called with nonpositive maxsize! \n"); s0.maxlen = 0; s0.str = 0; } else { s0.maxlen = maxsize; s0.str = calloc (maxsize+1, sizeof (char)); } return s0; } void free_string (mystring s0) { free (s0.str); s0.maxlen = 0; } void read_string2 (mystring * ps2) { if (!ps2) fprintf (stderr, "read_string2 called with string pointer NULL ! \n"); else if (ps2->str == 0) fprintf (stderr, "read_string2 called with unallocated mystring ! \n"); else { // PRECONDITION: ps2 is already allocated. int i; for (i=0; i < ps2->maxlen; i++) { int ch = getchar(); if (isspace (ch)) break; ps2->str[i] = ch; } ps2->str[i] = '\0'; // POSTCONDITION: *ps2->str is a valid C string of length <= maxlen; } } void prompt_read_string (mystring * ps3) { printf ("Please type in a string: "); read_string2 (ps3); } void write_string (mystring s0) { if (!s0.str) fprintf (stderr, "write_string called with unallocated mystring! \n"); else { int i; for (i=0; i < s0.maxlen && s0.str[i] != '\0'; i++) putchar (s0.str[i]); } } void write_named_string (char name3[], mystring s7) { printf ("mystring %s = `", name3); write_string (s7); printf ("' \n"); } // EOF mystring.c