【问题标题】:Reverse a string given its parameter反转给定参数的字符串
【发布时间】:2016-03-27 18:30:13
【问题描述】:

我想编写一个函数 void reverse_string(char* s) 来反转作为参数提供给它的以空字符结尾的 C 字符串的内容。

所以我让它在没有参数的情况下反转内容。但我想知道如何从命令行实现参数。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverseString(char* str);
int main()
{
    char str [256];
    strcpy_s(str, "Hello World");
    printf(str);
    reverseString(str);
    return 0;
}
void reverse_String(char* str)
{
    int i, j;
    char temp;
    i=j=temp=0;

    j=strlen(str)-1;
    for (i=0; i<j; i++, j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
    printf(str);
}

感谢任何帮助。

【问题讨论】:

标签: c string function


【解决方案1】:

这样做:

int main ( int argc, char **argv ) {
     char str [256];
     if(argc > 1)
       strcpy(str, argv[1]);
     else
       printf("no cmd given\n");
     ...
     return 0;
}

但是,您的代码在发布时不应该编译...这里有一些开始:

gsamaras@gsamaras:~$ gcc -Wall px.c 
px.c: In function ‘main’:
px.c:8:5: warning: implicit declaration of function ‘strcpy_s’ [-Wimplicit-function-declaration]
     strcpy_s(str, "Hello World");
     ^
px.c:9:5: warning: format not a string literal and no format arguments [-Wformat-security]
     printf(str);
     ^
px.c: In function ‘reverse_String’:
px.c:19:14: error: ‘str’ undeclared (first use in this function)
     j=strlen(str)-1;
              ^
px.c:19:14: note: each undeclared identifier is reported only once for each function it appears in

【讨论】:

  • 我修复了原始问题中的一些错误。我在函数中的参数是“char* s”,将其更改为“char* str”
  • 好的@shawnedward,也检查其他警告。至于 cmd 处理,我的回答应该足够了。 :)
  • strcpy_s() 是否像您在示例中显示的那样被调用?我在上面看到的所有文档都显示了三个参数(即中间的限制)。我不熟悉这个函数,这就是我问的原因。
【解决方案2】:
void reverse_String(char* string);

int main(int argc, char *argv[])
{
    char string[1024];

    if (argc > 1 && strlen(argv[1]) < 1024) {
        strcpy(string, argv[1]);
        printf("%s\n", string);
        reverse_String(string);
        printf("%s\n", string);
    } else {
        // appropriate error message to stderr and then:
        return 1;
    }

    return 0;
}

void reverse_String(char *string)
{
    // implement reversal but don't print it, leave that to main()
}

【讨论】:

  • 一个问题。为什么你在顶部初始化函数,然后在底部又得到它。你能把函数放在底部而不在顶部初始化吗?
  • 第一次调用是前向声明,让main() 知道reverse_String() 的签名(返回类型和参数)。您可以忽略它,但是您需要颠倒这两个函数的顺序,以便在 main() 引用它之前定义 reverse_String()。您的原始代码也尝试这样做,但没有使用一致的函数名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2021-11-11
  • 1970-01-01
  • 2016-01-06
  • 2022-12-05
  • 2020-05-21
  • 2012-09-15
相关资源
最近更新 更多