Using ampersand in scanf ()

When I compile scanf("%s", &var);, gcc sends a warning:

warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’

however, when I compile scanf("%s", var);, the warning does not apply. Both parts of the code work and the book I am reading specifically talks about using ampersand, but even in some examples this does not happen.

My question is: should I continue to use ampersand even if the book has not indicated?

+3
source share
4 answers

From what you posted varis a char array. In this case, you do not need an ampersand, just the name varwill be evaluated as (char *) as needed.

More details:

scanf , . , , . - char var[100], 100 char var [0] char var [99], 100- char. , &var[0], , , scanf. , , , scanf("%s", var);, , scanf , , 101, , , , . , , fgets, .

+4

& scanf("%s", &var);, scanf("%s", var);.

+1

, :

char name[20];

, , 20 . , , char : & name [i].
scanf , char C. scanf, , . , . , , . :

char myChar;
scanf("%c", &myChar);

, .

0

Source: https://habr.com/ru/post/1736818/


All Articles