ZBLOG

#include #define MAXSIZE 100 char* get_english(int n); int main() { int n = 0; printf("请输入一个非负整数:"); scanf("%d", &n); char* str = get_english(n); printf("该整数的英文描述为:%s", str); return 0; } char* get_english(int n) { char* num1[MAXSIZE] = {...

问题出在对于字符串数组的定义和赋值上。在原代码中,使用了指针数组来存储字符串,但是并没有为每个字符串分配内存空间。因此,在运行时会导致未定义的行为。

以下是修复后的代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAXSIZE 100
  4. char* get_english(int n);
  5. int main()
  6. {
  7. int n = 0;
  8. printf("请输入一个非负整数:");
  9. scanf("%d", &n);
  10. char* str = get_english(n);
  11. printf("该整数的英文描述为:%s\n", str);
  12. free(str); // 释放内存
  13. return 0;
  14. }
  15. char* get_english(int n)
  16. {
  17. char* num1[MAXSIZE] = {" ", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
  18. char* num2[MAXSIZE] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
  19. "Seventeen", "Eighteen","Nineteen"};
  20. char* num3[MAXSIZE] = {"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
  21. int thousands = n / 1000;
  22. int hundreds = (n % 1000) / 100;
  23. int tens = (n % 100) / 10;
  24. int ones = n % 10;
  25. static char str[MAXSIZE] = {0};
  26. int index = 0;
  27. if (n == 0)
  28. {
  29. return "Zero";
  30. }
  31. if (thousands != 0)
  32. {
  33. index += sprintf(str, "%s Thousand ", num1[thousands]);
  34. }
  35. if (hundreds != 0)
  36. {
  37. index += sprintf(str + index, "%s Hundred ", num1[hundreds]);
  38. }
  39. if (tens == 1)
  40. {
  41. index += sprintf(str + index, "%s ", num2[ones]);
  42. }
  43. else
  44. {
  45. if (tens != 0)
  46. {
  47. index += sprintf(str + index, "%s ", num3[tens - 1]);
  48. }
  49. if (ones != 0)
  50. {
  51. index += sprintf(str + index, "%s ", num1[ones]);
  52. }
  53. }
  54. str[index] = '\0';
  55. return strdup(str); // 使用strdup分配并复制字符串,需要在使用后手动释放内存
  56. }

修复后的代码使用strdup()函数来为返回的字符串分配内存,并通过free()函数在主函数中释放。此外,在处理十位数和个位数时也做了相应修改。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=2118

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?