C: modify array specifec charin c

Viewed 25

in this C code why I can't change the value of element a[0] and I just can enter it one time? and what should I do if I want to change the value of the element a[0]?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
char a[20];
char* p;

void klam(void) {
p = a;
scanf("%c", &p[0]);
scanf("%c", &p[0]);
 }
 int main() {

 klam();
 printf("%c", a[0]);
}
1 Answers

Within the function

void klam(void) {
p = a;
scanf("%c", &p[0]);
scanf("%c", &p[0]);
 }

the element p[0] is modified twice. It seems that in the second call it is set by the new line character '\n' that is placed in the input buffer after pressing the Enter key.

Here is a demonstrative program that shows the problem.

#include <stdio.h>

int main(void) 
{
    char c;
    
    scanf( "%c", &c );
    printf( "The code of the character c is %d\n", c );

    scanf( "%c", &c );
    printf( "The code of the character c is %d\n", c );

    return 0;
}

If to enter the character A and then to press the Enter key then the program output will be

The code of the character c is 65
The code of the character c is 10

where 65 is the ASCII code of the letter A and 10 is the code of the new line character '\n'.

Rewrite the function the following way

void klam(void) {
p = a;
scanf(" %c", &p[0]);
 }

or like

void klam(void) {
p = a;
scanf(" %c", &p[0]);
scanf(" %c", &p[0]);
 }

Pay attention to the blank before the conversion specifier %c within the call of the function scanf. It allows to skip white spaces.

Related