0

I'm banging my head on this problem, which occurred during a competition: I need to find the last three characters from a given word.

The 'findLeast' function has been wrote to achieve this by finding the '\0' character in the string passed as first argument through std library function strchr: Being the first argument a string, it is supposed to have the '\0' terminating character, whose reference is assigned to the string passed as second argument. That string is then decremented to point at the last three characters.

Skipping the isRime function, which only finds whether the last characters found in two string are equal or not, the problem lays there: when the first occurrence of the 'findLeast' function execute, the last three characters are effectively found, but when 'findLeast' is called again, it seems to return just a '\0' or the NULL default pointer. How can this be possible?

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

int isRime(char *firstLine, char *secondLine);

int main(){

    char *line = "Programming";
    char *line2 = "Learning";

    puts(line);

    printf("NUL character (the least): %s,last three characters: %s\n", strchr(line, '\0'), strchr(line, '\0') - 3);

    printf("%d\n", isRime(line, line2));

    return 0;
}

int isRime(char *firstLine, char *secondLine){

    #define RIME_SIZE 3

    void findLeast(const char *line, char *lastThree);

    char *buffer1;   
    char *buffer2;

    findLeast(firstLine, buffer1);
    puts(buffer1);
    findLeast(secondLine, buffer2);
    //buffer2 = (strchr(secondLine, '\0')) - 3; /*another way to achieve this*/
    puts(buffer2);

    if(!strcmp(buffer1, buffer2)){

        return 1;
    }

    return 0;
}

void findLeast(const char *line, char *lastThree){

    lastThree = strchr(line, '\0');

    lastThree -= 3;

    /*puts(lastThree);*/

    return;
}

Thanks for your attention!

Xedra
  • 1

0 Answers0