这是代码,它应该反转字符串。
#include <stdio.h>
void StrRev(char str[]) {
int len=strlen(str);
char out[len];
int i;
for(i=0;i<len;i++){
out[i]=str[len-i-1];
}
printf("%s",out);
}
int main(void) {
StrRev("TestString");
return 0;
}
预期输出:
gnirtStseT
实际输出:
gnirtStseT@
其他输入也会发生同样的情况,而其他输入则不会。
在 Code::Blocks 上使用 MingW 编译
最佳答案
两个问题:
您未能#include <string.h>
,因此没有 strlen
的声明。所以该函数被隐式声明为 int strlen()
。因此,将其添加到文件顶部。
您也没有将空终止字符添加到反转字符串中。
在for
之后循环中,将数组中的一个附加字符设置为 0。此外,您还需要将数组增大一以适应它。
#include <stdio.h>
// import declaration of strlen
#include <string.h>
void StrRev(char str[]) {
int len=strlen(str);
char out[len+1]; // increase length to make room for null terminator
int i;
for(i=0;i<len;i++){
out[i]=str[len-i-1];
}
out[i]=0; // add null terminator
printf("%s",out);
}
int main(void) {
StrRev("TestString");
return 0;
}
关于c - Printf 有时会写入额外的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38335928/