|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这个代码是运用动态内存知识实现对输入的字符串反向打印的功能,请问为什么我打印出来之后永远多一个% 在后面呀 一脸新手懵逼
- #include "stdio.h"
- #include "stdlib.h"
- #include "string.h"
- int countp = 0;
- char *get_reverse(void);
- void printc(char *p, int count);
- int main(void)
- {
- char *p = NULL;
- p = get_reverse();
- printc(p, countp);
- return 0;
- }
- char *get_reverse(void)
- {
- char ch;
- char *p = NULL;
- char *dp = NULL;
- int count = 0, i = 0;
- printf("Please enter char:");
- while((ch = getchar()) != '\n')
- {
- count++;
- p = (char *)realloc(p, count);
- p[count - 1] = ch;
- }
- dp = (char *)malloc(count + 1);
- dp[count] = '\0';
- countp = count;
- for(i = 0; count > 0; i++, count--)
- {
- dp[i] = p[count - 1];
- }
- free(p);
- return dp;
- }
- void printc(char *p, int count)
- {
- int i;
- printf("Reversed char is:");
- for(i = 0; i < count; i++)
- {
- printf("%c", p[i]);
- }
- putchar("\n");
- }
复制代码
putchar 函数用于输出单个字符,而不是字符串。
在C语言中,字符串是以 '\0' (空字符)结尾的字符数组
使用 putchar("\n") 时,编译器会给出一个警告,因为试图将字符串而不是单个字符传递给 putchar。
正确的方式是使用 putchar('\n') 来输出一个换行符,或者您可以使用 printf("\n")。
- void printc(char *p, int count)
- {
- int i;
- printf("Reversed char is:");
- for(i = 0; i < count; i++)
- {
- printf("%c", p[i]);
- }
- printf("\n"); // 或者 putchar('\n');
- }
复制代码
|
-
|