Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

arrays - warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)’

I am trying to run a simple C program but I am getting this error:

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

Running Mac OSX Mountain Lion, compiling in terminal using gcc 4.2.1

#include <stdio.h>

int main() {
    char me[20];

    printf("What is your name?");
    scanf("%s", &me);
    printf("Darn glad to meet you, %s!
", me);

    return (0);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
scanf("%s",&me);

should be

scanf("%s",me);

Explaination:

"%s" means that scanf is expecting a pointer to the first element of a char array. me is an object array and could evaluated as pointer. So that's why you can use me directly without adding &. Adding & to me will be evaluated to ‘char (*)[20]’ and your scanf is waiting char *

Code critic:

Using "%s" could cause a buffer overflow if the user input string with length > 20. So change it to "%19s":

scanf("%19s",me);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...