Array initialization question

Robert Carey carey at eniac.seas.upenn.edu
Fri May 17 23:08:31 AEST 1991


In article <16161 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
>In article <13193 at dog.ee.lbl.gov> torek at elf.ee.lbl.gov (Chris Torek) writes:
>>(Some argued that this was a misfeature, ...
>
>However, it was well-established existing practice in UNIX C compilers
>(among others).

As Chris Torek correctly pointed out:

  "The ANSI C standard (X3.159-1989) explicitly says that if you use a
  string literal as an initializer for a character array and you have
  specified the size of the array and the string literal exactly fills
  the array when the trailing '\0' character is dropped, that is what you
  get."

SunOS, at least, handles this inconsistently:

    $ cat foo.c
    main()
    {
        static char foo[2][5]={"12345", "67890"};

        printf("[%s][%s]\n", foo[0], foo[1]);
    }
    $ cc -o foo foo.c
    $ ./foo
    [1234567890][67890]
    $ cat bar.c
    main()
    {
         static char foo[5]="12345";
         static char bar[]="abc";
    
         printf("%s\n", foo);
    }
    $ cc -o bar bar.c
    "bar.c", line 3: too many initializers
    $ ./bar
    ./bar: command not found

Then again, the Sun C compiler is not an ANSI compiler.  It looks like
gcc handles the second example correctly:

    $ gcc -o bar bar.c
    $ ./bar
    12345abc
    $



More information about the Comp.lang.c mailing list