我正在编写一个程序,它将一些文件作为参数并反转打印所有行。问题是我得到了意想不到的结果:
如果我将它应用于包含以下行的文件
one
two
three
four
我得到了预期的结果,但是如果文件包含
september
november
december
返回
rebmetpes
rebmevons
rebmeceds
我不明白为什么最后要加一个“s”
这是我的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char *word);
int main(int argc, char *argv[], char*envp[]) {
/* No arguments */
if (argc == 1) {
return (0);
}
FILE *fp;
int i;
for (i = 1; i < argc; i++) {
fp = fopen(argv[i],"r"); // read mode
if( fp == NULL )
{
fprintf(stderr, "Error, no file");
}
else
{
char line [2048];
/*read line and reverse it. the function reverse it prints it*/
while ( fgets(line, sizeof line, fp) != NULL )
reverse(line);
}
fclose(fp);
}
return (0);
}
void reverse(char *word)
{
char *aux;
aux = word;
/* Store the length of the word passed as parameter */
int longitud;
longitud = (int) strlen(aux);
/* Allocate memory enough ??? */
char *res = malloc( longitud * sizeof(char) );
int i;
/in this loop i copy the string reversed into a new one
for (i = 0; i < longitud-1; i++)
{
res[i] = word[longitud - 2 - i];
}
fprintf(stdout, "%s\n", res);
free(res);
}
(注意:为清楚起见,删除了一些代码,但应该可以编译)
最佳答案
您忘记以 \0
字符结束您的字符串。在反转字符串时,\0
成为反转字符串的第一个字符。首先为比你分配的多一个字符分配内存
char *res = malloc( longitud * sizeof(char) + 1);
然后试试这个
for (i = 0; i < longitud-1; i++)
{
res[i] = word[longitud - 2 - i];
}
res[i] = '\0'; // Terminating string with '\0'
关于c - 在 C 中反向打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20143223/