user7163080 user7163080 - 22 days ago 5
C Question

parameter is modified after scanf

I'm pretty new to c and I've been finding that after using the scanf function my char *string parameter gets modified, the input to c doesn't change the end output nor does the actual parameter. though it does seem what comes next in the code does change the final output. i can't find any example of this happening online does anybody know what this is? my only thought is that im missing something but i can't see what it is

#include <stdio.h>
#include <stdlib.h>

int method1(char *string){
char c;
printf("enter(y/n): ");
scanf("%s", &c);
printf("%s\n", string);
return 0;
}

int main() {
char *string = "string";
printf("%s\n", string);
method1(string);
return 0;
}


output:
string
enter(y/n): y ā–’Eā–’

usr usr
Answer

c can hold just a single char. But

scanf("%s", &c);

will read multiple characters and there's no room for that in c. Hence, it's undefined behaviour. Even if you input just 1 char, %s will still require a space for the terminating null byte.

If you just want to read a single character then you can use fgets() as below:

char c[2];
if (fgets(c, sizeof c, stdin)) {
  /* c[0] contains your input 'y' or 'n' */
}

Always avoid scanf(). See: Why does everyone say not to use scanf? What should I use instead?