names3.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // names3.c -- use pointers and malloc()
  2. #include <stdio.h>
  3. #include <string.h> // for strcpy(), strlen()
  4. #include <stdlib.h> // for malloc(), free()
  5. #define SLEN 81
  6. struct namect {
  7. char * fname; // using pointers
  8. char * lname;
  9. int letters;
  10. };
  11. void getinfo(struct namect *); // allocates memory
  12. void makeinfo(struct namect *);
  13. void showinfo(const struct namect *);
  14. void cleanup(struct namect *); // free memory when done
  15. char * s_gets(char * st, int n);
  16. int main(void)
  17. {
  18. struct namect person;
  19. getinfo(&person);
  20. makeinfo(&person);
  21. showinfo(&person);
  22. cleanup(&person);
  23. return 0;
  24. }
  25. void getinfo (struct namect * pst)
  26. {
  27. char temp[SLEN];
  28. printf("Please enter your first name.\n");
  29. s_gets(temp, SLEN);
  30. // allocate memory to hold name
  31. pst->fname = (char *) malloc(strlen(temp) + 1);
  32. // copy name to allocated memory
  33. strcpy(pst->fname, temp);
  34. printf("Please enter your last name.\n");
  35. s_gets(temp, SLEN);
  36. pst->lname = (char *) malloc(strlen(temp) + 1);
  37. strcpy(pst->lname, temp);
  38. }
  39. void makeinfo (struct namect * pst)
  40. {
  41. pst->letters = strlen(pst->fname) +
  42. strlen(pst->lname);
  43. }
  44. void showinfo (const struct namect * pst)
  45. {
  46. printf("%s %s, your name contains %d letters.\n",
  47. pst->fname, pst->lname, pst->letters);
  48. }
  49. void cleanup(struct namect * pst)
  50. {
  51. free(pst->fname);
  52. free(pst->lname);
  53. }
  54. char * s_gets(char * st, int n)
  55. {
  56. char * ret_val;
  57. char * find;
  58. ret_val = fgets(st, n, stdin);
  59. if (ret_val)
  60. {
  61. find = strchr(st, '\n'); // look for newline
  62. if (find) // if the address is not NULL,
  63. *find = '\0'; // place a null character there
  64. else
  65. while (getchar() != '\n')
  66. continue; // dispose of rest of line
  67. }
  68. return ret_val;
  69. }