2

If I have below string in C:

char s[]="Question";

Then I noted that both of the below prtintf prints the string correctly in terminal.

1.

printf("%s\n",s);

2.

printf("%s\n",&s);

Which is a correct way to print the string in C. If both of them are same, then what is the convention followed ? 1 or 2 ?

Thanks.

sps
  • 2,720
  • 2
  • 19
  • 38
  • 3
    The second one is undefined behavior. The first one is correct. [C-faq 12.12b](http://c-faq.com/stdio/scanf1a.html) –  Feb 09 '15 at 02:04
  • 1
    possible duplicate of [Why doesn't scanf need an ampersand for strings and also works fine in printf (in C)?](http://stackoverflow.com/questions/1931850/why-doesnt-scanf-need-an-ampersand-for-strings-and-also-works-fine-in-printf-i) – P0W Feb 09 '15 at 02:17
  • the name of an array, in C, degrades to the address of the array. so printf( "%s", array ) is correct. using printf("%s", &array); is saying print the address of the address of the array, which is not defined and can/will lead to a seg fault event. – user3629249 Feb 09 '15 at 04:07

2 Answers2

5
char s[]="Question";
printf("%s\n",&s);

is undefined behavior because,

§7.21.6.1/8 The conversion specifiers and their meanings are:

[...]

s          If no l length modifier is present, the argument shall be a pointer to the initial element of             an array of character type.

§7.21.6.1/9 [...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

s in this context will decay to a pointer type. Since & yields a pointer, the type you're passing to printf is actually a pointer to a pointer.

0

The first one is correct, for the second one you should get a warning from your compiler, since it's UB, something like:

[Warning] format '%s' expects argument of type 'char *'
Rizier123
  • 58,877
  • 16
  • 101
  • 156