c - %s expects 'char *', but argument is 'char[100]' -


i have along lines of:

#include <stdio.h> typedef struct { char s[100]; } literal;  literal foo() { return (literal) {"foo"}; }  int main(int argc, char **argv) {     printf("%s", foo().s);     return 0; } 

and error when compiling (with gcc):

warning: format ‘%s’ expects argument of type ‘char *’, argument 2 has type ‘char[100]’ [-wformat=]

any1 has ideas on how can fix it? , wrong function return type?

edit problem (if not clear in discussion) c standard gcc using compile file. if use -std=c99 or -std=c11 works.

it not error warning, not warnings -wall produces sensible.

here compiler "kind-of" right: before evaluation argument array , not pointer, , taking address of temporary object bit dangerous. managed rid of warning using pointer explicitly

printf("%s\n", &foo().s[0]); 

also should notice using rare animal, namely object of temporary lifetime, return value or function. since c99, there special rule allows take address of such beast, corner case of c language, , better off using simpler construct. lifetime of pointer ends end of expression. if try assign pointer variable, say, , use later on in expression, have undefined behavior.

edit(s): remarked mafso in comment, c versions before c99, not allowed take address of return value of function. pascal cuoq notes, behavior of code undefined c99, because between evaluation of arguments , actual call of function there sequence point. c11 rectified indroducing object of temporary lifetime mentioned above.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -