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

Time:09-15

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:

output of code

CodePudding user response:

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);
  •  Tags:  
  • c
  • Related