python小菜 2018-10-29 04:10 采纳率: 0%
浏览 351
已采纳

C 反向字符串[暂停]

I have the following code where Index is defined as length- 1. It prints an extra space in the beginning if I dont include the - 1. Why is the -1 required in the code?

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

int main()
{
   char s[200];
   int index, lenght;

   printf("Input a string\n");
   gets(s);

   // Calculating string length
   length = strlen(s);
    index=length-1;
   while (index >=0) {

    printf("%c", s[index]);
    index--;
   }
   printf("\n");
   return 0;
}

转载于:https://stackoverflow.com/questions/53038637/c-reverse-string

  • 写回答

4条回答 默认 最新

  • 狐狸.fox 2018-10-29 04:14
    关注

    Indexes always start from 0. So if strlen() function returns the length x that means its length is x and you have to iterate from 0 to x-1. Thats why you have to include -1. On index x there will be some garbage or space.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器