函数'strrev'的隐式声明

时间:2014-10-28 21:35:02

标签: c palindrome implicit-declaration

关于为什么当我尝试编译代码以检查来自文件atadata的行是否收到警告时的任何想法:

  

warning: implicit declaration of function ‘strrev’ [-Wimplicit-function-declaration]

CODE

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

int main(){
    char palindromes[100];
    char reverse[100];
    FILE *atadata = fopen("atadata","r");
    while (fgets(palindromes,sizeof(palindromes),atadata) != NULL){
        strcpy(reverse,palindromes);
        strrev(reverse);
        if( strcmp(atadata,reverse) == 0)
        fputs(atadata, stdout);
    }
    fclose(atadata);
    return 0;
}

4 个答案:

答案 0 :(得分:3)

char *strrev(char *str){
    char c, *front, *back;

    if(!str || !*str)
        return str;
    for(front=str,back=str+strlen(str)-1;front < back;front++,back--){
        c=*front;*front=*back;*back=c;
    }
    return str;
}

答案 1 :(得分:2)

如果您在Linux中进行编译,则strrev()not part of string.h。链接的问题包含一个answer链接到源代码,您可以将其直接带入您自己的代码中。

答案 2 :(得分:1)

一个能满足您需求并且运行效率高的功能将采用以下形式:

/** strrev - reverse string, swaps src & dest each iteration.
*  Takes valid string and reverses, original is not preserved.
*  If str is valid, returns pointer to str, NULL otherwise.
*/
char *
strrev (char *str)
{
    if (!str) { 
        fprintf (stderr, "%s() Error: invalid string\n", __func__); 
        return NULL; 
    }

    char *begin = str;
    char *end = str + strlen (str) - 1;
    char tmp;

    while (end > begin)
    {
        tmp = *end;
        *end-- = *begin;
        *begin++ = tmp;
    }

    return str;
}

答案 3 :(得分:0)

如果其他一些代码难以阅读或者您不知道如何使用指针,这里有一个简短的脚本来反转字符串。

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

int main(void)
{
// Start here
char String1[30] = "Hello",reversed[30];
int i;
long int length = strlen(String1);

//Reverse string
for(i=0; i<length; ++i)
{
    reversed[length-i-1] = String1[i];
}

printf("First string %s\n",String1);
printf("Reversed string %s\n",reversed);

// To here if you want to copy and paste into your code without making functions 
return 0;
}