|
|
发表于 2023-1-2 13:39:04
|
显示全部楼层
本楼为最佳答案
- #include<stdio.h>
- #include<stdlib.h>
- #define INCREMENT 10
- #define INIT_SIZE INCREMENT
- int main()
- {
- char ch;
- char *str;
- char *last;
- int limit = 0;
- int index = 0;
- int times = 1;
- int count = 0;
-
- //str = (char *)malloc(sizeof(char) * INCREMENT);
- str = malloc(INCREMENT); // 没有必要强制转换,没有必要乘以sizeof(char)
- // 因为 sizeof(char) == 1
-
- if(str == NULL)
- {
- exit(1);
- }
-
- last = str;
- limit = INCREMENT;
-
- printf("请输入一个字符串:");
-
- while((ch = getchar()) != '\n')
- {
- last[index++] = ch;
- if(index >= limit)
- {
- //str = (char *)realloc(str, INCREMENT * times + INCREMENT);
- str = realloc(str, INCREMENT * times++ + INCREMENT);
- last = str;
- limit += INCREMENT;
- }
- count++;
- }
-
- last[index] = '\0';
-
- printf("反转后的结果是:");
- for(int i = count;i >= 0;i--)
- {
- printf("%c", str[i]);
- }
-
- free(str); // 内存也不释放?谁教给你的?
- printf("\n"); // 行也不换
-
- return 0;
- }
复制代码 |
|