字符回显的基础问题

Rookiekk 2017-02-22 06:30:36
#include<stdio.h>
#include<string.h>

int main()
{
char ch[20],c;
int i,n;

printf("enter a row:");
for(i=0;(ch[i]=getchar())!='\n';i++)
;
printf("reshow:");
n=strlen(ch);
printf("%d\n",n);
for(i=1;i<=n;i++)
{
printf("%c",ch[n-i]);
}
printf("\n");
return 0;
为什么打印出来会有一行不明的字符,而且输出的字符个数也不对。。 错在哪求指点
}
...全文
232 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Pingo520 2017-02-24
  • 打赏
  • 举报
回复
越界了吧,你ch定义的大小是20,你用strlen求出的是23,而且你还没有结束符
自信男孩 2017-02-23
  • 打赏
  • 举报
回复

#include<stdio.h>
#include<string.h>

int main()
{
    char ch[20];
    int i, len;

    printf("enter a row:");
    for(i = 0; (ch[i]=getchar()) !='\n'; i++)
        ;
    ch[i] = 0; /* add '\0' */
    printf("reshow:");
    len = strlen(ch);
    printf("%d\n", len);
    for(i = 1; i <= len; i++) {
        printf("%c", ch[len-i]);
    }
    printf("\n");
    return 0;
}
一般遇到输出字符串时出现乱码,基本上都是没有加上字符串结束标记;建议下次遇到类似问题先检查字符串结束标识是否存在。
小灸舞 版主 2017-02-23
  • 打赏
  • 举报
回复
Debug模式下C程序,发现栈区开辟的存储空间都是使用0CCCCCCCCh来填充4字节单位的,也就是说,栈区开辟的存取局部变量的空间的每一个字节都被0xCC填充了。(为什么用0xCC,这个是int 3h的机器码,下断点用的)两个0xCC合起来输出时恰好对应中文“烫”字。动态分配的空间开辟的堆,VC的Debug用0xCD填充堆的空间,两个0xCD和在一起就是屯了。
ck2333 2017-02-23
  • 打赏
  • 举报
回复
你的输入为什么要这样呢,既然是想输入字符串,就直接scanf("%s",ch);不就行了
赵4老师 2017-02-23
  • 打赏
  • 举报
回复
windows里常见的内存填充数据含义
 * 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
漱 * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
涵?  * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
很?  * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
撅饰 * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
烫烫 * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
屯屯 * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
葺葺 * 0xDDDDDDDD : Used by Microsoft's free() or delete to mark freed heap memory
蕲蕲 * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash
 * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
 * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
paschen 2017-02-22
  • 打赏
  • 举报
回复
字符串要以\0结尾 for(i=0;(ch[i]=getchar())!='\n';i++) ; 这句后面加上: ch[i] = '\0';
幻夢之葉 2017-02-22
  • 打赏
  • 举报
回复
for(i=0;(ch[i]=getchar())!='\n';i++) ; ch[i] = '\0'; 设置字符串结束标志
ghost129 2017-02-22
  • 打赏
  • 举报
回复
字符数组末尾没有 ‘\0’ 结束符,这样 strlen 求出来的值自然就不对,而且还把回车符算进去了

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧