c - 使用 while 循环反转 c 中的字符串

标签 c

我正在刷新我的 C 知识,我碰巧遇到了这个程序来反转字符串。我有一种感觉,最终反转字符串的最后一个字符应该被分配 '\0' 值,否则它可能有一个垃圾值。请问这段代码是否正确或者需要修改吗?提前致谢!

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

void main()
{
  char str[100],temp;
  int i,j=0;

  printf("nEnter the string :");
  gets(str);

  i=0;
  j=strlen(str)-1;

  while(i<j)
  {
    temp=str[i];
    str[i]=str[j];
    str[j]=temp;
    i++;
    j--;
  }

  printf("nReverse string is :%s",str);
  return(0);
}

最佳答案

根据人得到:

...the buffer is terminated with a 0.

我想你已经准备好了!

关于c - 使用 while 循环反转 c 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22256442/

相关文章:

c - C 中的激活记录

c - C 字符串中的子字符串替换

c - xmlNodeGetContent 引入换行符

c - STM32写Flash

c - 在C中将数组中的两个索引合并为一个

c - 在 C 中定义整数范围

c - 串行编程 - Termios。从设备读取 0x00 字节时卡住

c - 使用 Malloc() 使用指针创建整数数组

C - 如何向网站发送正确的 HEAD 请求?

c++ - 为什么将单个枚举封装在一个结构中?