Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the second "a" have different value than the first "a"?

I’m trying to get the difference of two characters.
My problem is when I input the 2nd character it gives a different value even if the character is just the same as the first input:

Example below. I input "a" as first char and then "a" again for the second but it gives different value

int main(){

    
    char* flet;
    char* slet;
   
    printf("Input first character:");
    scanf("%c", &flet);

    fflush(stdin);

    printf("Input Second character:");
    scanf("%c", &slet);

    printf("First Char is \"%c\" and Second Char is \"%c\".", flet,slet);

    DiffofChar(flet,slet);
}

void DiffofChar(char* letter1, char* letter2){
    int theDiff;
    theDiff = letter1 - letter2;
    printf("The difference of %c (%d) and %c (%d) is %d.", letter1, letter1, letter2, letter2, theDiff);
}

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

output of code

>Solution :

This is incorrect:

char* flet;
char* slet;

printf("Input first character:");
scanf("%c", &flet);

At best, the above will cast the character value typed (a) into a pointer and that address (0x61 == 'a') will just be a pointer value for an invalid memory location.

The fix is to declare the variables as just type char. You still pass &flet and &slet to the scanf functions.

char flet;
char slet;

printf("Input first character:");
scanf("%c", &flet);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading