字符串逆序输出.c 761 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int main() {
  5. char *str;
  6. int length;
  7. int i;
  8. str = (char *)malloc(101);
  9. if (str == NULL) {
  10. fprintf(stderr, "内存分配失败\n");
  11. exit(EXIT_FAILURE);
  12. }
  13. fgets(str, 101, stdin); //
  14. if (str[strlen(str) - 1] == '\n') {
  15. str[strlen(str) - 1] = '\0';
  16. }
  17. length = strlen(str);
  18. char *reversed = (char *)malloc((length + 1) * sizeof(char));
  19. if (reversed == NULL) {
  20. fprintf(stderr, "内存分配失败\n");
  21. exit(EXIT_FAILURE);
  22. }
  23. for (i = 0; i < length; i++) {
  24. reversed[i] = str[length - 1 - i];
  25. }
  26. reversed[i + 1] = '\0';
  27. printf("%s\n", reversed);
  28. free(reversed);
  29. free(str);
  30. return 0;
  31. }