【发布时间】:2013-10-27 22:19:56
【问题描述】:
我正在编写一个简单的 c 程序来反转字符串,从 argv[1] 中获取字符串。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* flip_string(char *string){
int i = strlen(string);
int j = 0;
// Doesn't really matter all I wanted was the same size string for temp.
char* temp = string;
puts("This is the original string");
puts(string);
puts("This is the \"temp\" string");
puts(temp);
for(i; i>=0; i--){
temp[j] = string[i]
if (j <= strlen(string)) {
j++;
}
}
return(temp);
}
int main(int argc, char *argv[]){
puts(flip_string(argv[1]));
printf("This is the end of the program\n");
}
基本上就是这样,程序编译和一切,但最后不返回临时字符串(只是空格)。一开始,当它等于字符串时,它会很好地打印温度。此外,如果我在 for 循环中逐个字符地执行 temp 的 printf ,则会打印出正确的临时字符串,即字符串 -> 反转。就在我尝试将其打印到标准输出(在 for 循环之后/或在 main 中)时,什么也没有发生,只打印空格。
谢谢
【问题讨论】:
-
我也在 Ubuntu 论坛上写过这篇文章,但认为这更像是一个一般性的编码问题。
-
你知道
temp和string指向同一个内存位置吗? -
别忘了接受 WhozCraig 的回答,这是做你想做的事的正确方法。干净整洁。
-
次要问题:不要在循环内长度不变的字符串上一遍又一遍地调用 strlen()。调用一次并存储结果。然后在循环中使用存储的值。