|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 gandixiwang 于 2022-9-13 14:39 编辑
- #include <stdio.h>
- #include <stdlib.h>
- #define INCREMENT 10
- #define INIT_SIZE INCREMENT
- char* long_count(char*);
- char* reversal(char*);
- char* long_count(char* num)
- {
- char ch;
- char *last=NULL; // 最近一次迭代的起始地址
- int limit = 0; // 每次迭代的限制值
- long times = 1; // 记录重新申请多少次内存
-
- num = (char *)malloc(INIT_SIZE);
- if (num == NULL)
- {
- exit(1);
- }
-
- last = num;
-
- printf("请输入一个整数:");
-
- while ((ch=getchar()) != '\n')
- {
- last[limit++] = ch;
- if (limit >= INCREMENT)
- {
- int offset = last - num;
- num = (char *)realloc(num, INIT_SIZE + INCREMENT * times++);
- last = num;
- last += offset;
- last += INCREMENT;
- limit = 0;
- }
- }
- last[limit] = '\0';
-
- return num;
- }
- char* reversal(char* num)
- {
- char* end=num;
- char temp=0;
- if(num!=NULL)
- {
- while(*end++ !='\0');//令end指向num字符串的末尾
- end-=2;
- for(int i=0,j=end-num;i<j;i++,j--)
- {
- temp=num[i];
- num[i]=num[j];
- num[j]=temp;
- }
- }
- printf("前后翻转后的结果:%s\n", num);
- return num;
- }
- int main(void)
- {
- char *num=NULL; // 存储整个数据的首地址
- num=long_count(num);
-
- num=reversal(num);
-
- return 0;
- }
复制代码
为什么 end 还要减去2才指向 num 末尾那个数啊?(第51行,我写的reversal函数中)
一般不是 end++ !='\0'
只要再自减1就能指向字符串末尾了吗?
我记得 char 类型非中文只占一个字节吧
执行到51行的时候,end已经指向 '\0' 后面的那个位置了,注意不是指向 '\0',是指向 '\0' 的后面
你可以调试程序,51行下断点,看看end指向了哪里
|
|