'ello all.
I am trying to get better with C and am taking one of laserlights suggestions by making a program to read a dictionary, find the palindromes and return the longest one.
Right now I am just trying to get my string reverse function to work.
It does reverse the string and return it, but there are junk values before and after the returned pointer.
Code:
#include <stdio.h>
#include <stdlib.h>
char* strrev(char *str){
int i = 0;
int length = strlen(str);
char *tmp = malloc(sizeof(char)*length);
while(*(str+i) != '\0'){
tmp[length - i] = *(str+i);
i++;
}
return tmp;
}
int main(int argc, char* argv[]){
char file[] = "c:\\dictionary.txt";
FILE *fp = fopen(file, "r");
if(fp != NULL){
char *line = malloc(sizeof(char)*1024);
int cnt = 0;
while(fgets(line, 1024, fp) != NULL){
printf("%s", line);
printf("%s\n", strrev(line));
++cnt;
if(cnt > 5) break;
}
} else {
perror("Could not open the file ");
}
fclose(fp);
system("PAUSE");
return 0;
}
Sorry I can't post up the dictionary, it is like 15MB. You can create dictionary.txt with each word on a new line to test it out.
Any help is appreciated. Any criticism about how I could do this better would be appreciated as well.