Reputation: 761
I have a reverse function that I would like to use to compare two strings against each other, but it doesn't seem to work. I think that every time the string is iterated over it overwrites the value every time. I'm think that it needs to be stored in a separate array to be able to evaluate the two against each other. Here's what I have so far:
int compare_strings(char [], char []);
char* reverse(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;
}
return str;
}
int main(int argc, char* argv []) {
char word[100];
char const* const fileName = argv[1];
FILE *file = fopen(fileName,"r");
char s[100];
char formattedWord[100];
while(fgets(word, 100, file)!=NULL){
memset(s,'\0',sizeof s);
char *token=strtok(word," ");
while(token!=NULL){
size_t n=strlen(s);
sprintf(&s[n],"%s",token);
token=strtok(NULL," ");
}
if (reverse(s) == s)
{
printf("%s\n", reverse(s));
}
}
fclose(file);
return 0;
}
Upvotes: 1
Views: 105
Reputation: 223689
There are three problems. First is this:
if (reverse(s) == s)
This is not how you compare two strings. You instead call strcmp
, and if it returns 0 the two strings are the same.
However, the reverse
function reverses the string in place. So with either method the result will always be true.
Inside of reverse
, you want to allocate new memory and write the reversed string there, then return that new string.
char* reverse(char* str)
{
int i, j;
char *temp;
i=j=0;
temp = malloc(strlen(str) + 1);
j=strlen(str)-1;
for (i=0; j>=0; i++, j--)
{
temp[j]=str[i];
}
temp[strlen(str)] = '\0';
return temp;
}
Now when you call reverse
, you need to save off the return value so you can free
that memory later.
char *s2;
...
s2 = reverse(s);
if (!strcmp(s,s2))
{
printf("%s\n", s2);
}
free(s2);
Finally, fgets
will append a newline to the end of the string to read if there's enough space for it. So you need to account for that when tokenizing the string:
char *token=strtok(word," \n");
while(token!=NULL){
size_t n=strlen(s);
sprintf(&s[n],"%s",token);
token=strtok(NULL," \n");
}
Upvotes: 2
Reputation: 1518
You can't do if (reverse(s) == s)
because that will simply compare the pointer values. You must use a library function such as strcmp
or to iterate through each char and compare them.
Something like this would be valid.
char *reverse_s = reverse(s);
if(!strcmp(reverse_s, s)) {
printf("%s\n", reverse_s);
}
Upvotes: 4