Reputation: 31
Any ideas on why when I try to compile this code to check if a line from the file atadata
I get the warning:
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;
}
Upvotes: 3
Views: 26661
Reputation: 84551
One function that will suit your needs and is efficient in its operation would take the following form:
/** 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 = *begin ? str + strlen (str) - 1 : begin; /* ensure non-empty */
char tmp;
while (end > begin)
{
tmp = *end;
*end-- = *begin;
*begin++ = tmp;
}
return str;
}
Upvotes: 0
Reputation: 879
Incase some of the other peices of code are hard to read or you do not know how to use pointers, here is a short script to reverse a string.
#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;
}
Upvotes: 1
Reputation: 40145
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;
}
Upvotes: 3
Reputation: 96937
If you are compiling in Linux, then strrev()
is not part of string.h. The linked question contains an answer linking to source for an implementation you can bring into your own code directly.
Upvotes: 4