Home>

In the reference book I'm using, there is an exercise "What is displayed when I enter a lowercase d in the code below", but when I enter it, I get a segmentation fault and I can't confirm it. What is displayed when I enter d? please tell me.

#include<stdio.h>
int main (void) {
char a;
int n;
scanf ("% c",&a);
n = a-'a';
printf ("% d \ n", n);
  return 0;
}
c
  • Answer # 1

    It seems that my computer has gone crazy, so I restarted it. I'm sorry.

  • Answer # 2

    I can't find anything strange in the code provided.
    Maybe something is strange somewhere else.

  • Answer # 3

    Hello.
    Since the char variable a is a 1-byte area, scanning a character string with scanf will cause memory corruption. The result is a segmentation fault. char a [16];/* Make an array (about 16 bytes for the time being) * / scanf ("% c", a);/* take&* / n = a [0]-'a';/* Change to the first element of the array * / If you execute it with this, the desired value will be displayed.

    Since it is% c, it does not destroy the memory. .. ..
    Why. .. ..