结构、指针和malloc()

作者:追风剑情 发布于:2020-3-9 18:08 分类:C

示例

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <ctype.h>
  7. //malloc()、free()
  8. #include <stdlib.h>
  9. #include <time.h>
  10.  
  11. #define SLEN 81
  12. struct namect {
  13. char * fname;
  14. char * lname;
  15. int letters;
  16. };
  17.  
  18. void getinfo(struct namect *);
  19. void makeinfo(struct namect *);
  20. void showinfo(const struct namect *);
  21. void cleanup(struct namect *);
  22. char * s_gets(char * st, int n);
  23.  
  24. //argc: 参数个数 argv[]: 参数数组
  25. //int main(int argc, char **argv)
  26. int main(int argc, char *argv[])
  27. {
  28. struct namect person;
  29.  
  30. getinfo(&person);
  31. makeinfo(&person);
  32. showinfo(&person);
  33. cleanup(&person);
  34.  
  35. system("pause");
  36. return 0;
  37. }
  38.  
  39. void getinfo(struct namect * pst)
  40. {
  41. char temp[SLEN];
  42. printf("Please enter your first name.\n");
  43. s_gets(temp, SLEN);
  44. // 分配内存
  45. pst->fname = (char *)malloc(strlen(temp) + 1);
  46. // 把名拷贝到动态分配的内存中
  47. strcpy(pst->fname, temp);
  48. printf("Please enter your last name.\n");
  49. s_gets(temp, SLEN);
  50. pst->lname = (char *)malloc(strlen(temp) + 1);
  51. strcpy(pst->lname, temp);
  52. }
  53.  
  54. void makeinfo(struct namect * pst)
  55. {
  56. pst->letters = strlen(pst->fname) +
  57. strlen(pst->lname);
  58. }
  59.  
  60. void showinfo(const struct namect * pst)
  61. {
  62. printf("%s %s, your name contains %d letters.\n",
  63. pst->fname, pst->lname, pst->letters);
  64. }
  65.  
  66. // 释放内存
  67. void cleanup(struct namect * pst)
  68. {
  69. free(pst->fname);
  70. free(pst->lname);
  71. }
  72.  
  73. char * s_gets(char * st, int n)
  74. {
  75. char * ret_val;
  76. int i = 0;
  77. ret_val = fgets(st, n, stdin);
  78. if (ret_val) //即,ret_val != NULL
  79. {
  80. while (st[i] != '\n' && st[i] != '\0')
  81. i++;
  82. if (st[i] == '\n')
  83. st[i] = '\0';
  84. else
  85. while (getchar() != '\n')
  86. continue;
  87. }
  88. return ret_val;
  89. }

运行测试

1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号