我正在写一个简单的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");
}
Run Code Online (Sandbox Code Playgroud)
基本上就是这样,程序编译并且一切都没有返回到最后的临时字符串(只是空格).在开始时,当它等于字符串时,它会打印temp.此外,如果我在for循环中使用temp的字符printf执行字符,则打印正确的临时字符串即字符串 - >反转.就在我尝试将其打印到标准输出时(在for循环之后/或在主循环中)没有任何反应只打印空白区域.
谢谢
你正朝着正确的方向试图使用指针.再多想一想,你可能会有它.安全实施如下:
#include <stdio.h>
char *flip_string(char *str)
{
char *lhs = str, *rhs = str;
if (!str || !*str || !*(str+1))
return str;
while (*++rhs); // rhs to eos
while (lhs < --rhs)
{
char tmp = *lhs;
*lhs++ = *rhs;
*rhs = tmp;
}
return str;
}
int main()
{
char test1[] = "Hello, World!";
char test2[] = "";
char test3[] = "1";
printf("%s, %s, %s\n", flip_string(test1), flip_string(test2), flip_string(test3));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
!dlroW ,olleH, , 1
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.