-4

One of my friends sent me this code today:

#include <stdio.h>

int main()
{
    char *s = { "one", "two", "three", "four", "five" };
    puts(s);
}

Its output is:

one

As I know, strings like "one" are translated as addresses in C, which are constants. Thus, "one", "two", "three", "four", "five" is equal to "five" due to comma operators among them. So shouldn't { "one", "two", "three", "four", "five" } be equal to { "five" },creating char *s="five"?

nalzok
  • 14,965
  • 21
  • 72
  • 139
  • 6
    Do you really want `char *s` instead of `char *s[]`? – ROMANIA_engineer Jan 14 '16 at 14:19
  • 1
    MSVC says error C2078: too many initializers. So the code cannot output `one` – Weather Vane Jan 14 '16 at 14:25
  • 1
    The commas in initialiser lists are not comma operators. They just separate the fields. but you can get the comma operator by surrounding expressions in parentheses: `char *s = { ("one", "two", "three") };` (And you'll get warnings that the void expressions to the left don't have any effect.) – M Oehm Jan 14 '16 at 14:26

1 Answers1

1

There is no comma operator anywhere in this code. Instead, the commas are seperators in an initializer list.

The compiler will initialize the char pointer to the first literal in the list and issue a warning like "excess elements in initializer", indicating that the remaining elements in the list have been discarded.

As was already mentioned in the comments, what your friend intended was probably

char *s[] = { "one", "two", "three", "four", "five" }

giving s[0]="one", s[1]="two" and so on.

Jochen Müller
  • 309
  • 1
  • 6
  • But when you change that the `puts(s)` causes a compiler warning and junk is printed. – Weather Vane Jan 14 '16 at 14:35
  • Yes, because s now points to an array of char pointers, while s[0], s[1] and so on point to the string literals. So puts(s) interprets the address data as a string and prints junk, while puts(s[0]) will print "one". – Jochen Müller Jan 14 '16 at 14:40