用C反向字符串 [英] Reverse strings in C
本文介绍了用C反向字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是与以下code中的问题?
What's the problem with the following code?
#define N 30
int main() {
char str[N], new_str[N];
int i,len;
printf("Please enter 20 letters. \n");
scanf("%s", str);
len = strlen(str);
printf("The length of str is %d ", len);
for (i=0; i< len; i++)
new_str[i]=str[len-1-i];
printf("The result is: %s\n", new_str);
return 1;
}
我检查下16个字符的字符串每次的程序确定,它上面返回末不确定的字符:
I checked that for every string under 16 characters the program is OK, and above it returns undefined characters at the end:
Please enter 20 letters.
1234567891111111
The result is: 1111111987654321q=V?.
不过,如果我初始化海峡,new_str
以问题就解决了。我仍然不知道是什么原因导致的问题。
However, if I initialize str, new_str
with "" the problem is solved. I still I wonder what causes the problem.
推荐答案
您需要添加空终止:
new_str[len] = '\0';
否则,是最后一个字符后的垃圾,因此字符串没有结束
otherwise, there is garbage after the last character, so the string is not ending
这篇关于用C反向字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文