Multi-dimensional array initialization

Doug Schmidt schmidt at siam.ics.uci.edu
Sun Jun 11 09:51:21 AEST 1989


I have a question concerning multi-dimensional array initalization.

Consider the following 2-dimensional array declaration:

----------------------------------------
typedef struct { int i; int j; } bar;

static bar foo[4][4]; /* 4 * 4 == 16 element array of `bar's. */
----------------------------------------

Now, let's assume that this array is given 16 initial values instead:

----------------------------------------
typedef struct { int i; int j; } bar;

static bar foo[4][4] =
{
  { {1,0},  {2,0},  {3,0},  {4,0}, },
  { {5,0},  {6,0},  {7,0},  {8,0}, },
  { {9,0}, {10,0}, {11,0}, {12,0}, },
  {{13,0}, {14,0}, {15,0}, {16,0}, },
}; 
----------------------------------------

Everything works as expected, the initializer has 4 explicitly
demarcated rows with 4 elements in each row.

Now, suppose that we leave out the explicit curly braces that demarcate rows,
i.e., certain '{' and '}':

----------------------------------------
static bar foo[4][4] =
{
  {1,0},  {2,0},  {3,0},  {4,0},  {5,0},  {6,0},  {7,0},  {8,0},
  {9,0}, {10,0}, {11,0}, {12,0}, {13,0}, {14,0}, {15,0}, {16,0},
};
----------------------------------------

There are still 16 array cells, and 16 initializer groups.

However, this initialization gives different results depending on
whether it is compiled with GCC 1.35 or Sun OS 4.0.1's cc compiler The
only difference is the absence of surrounding '{' '}' to demarcate
each row in the initializer for the two dimensional array `bar.'

  Can someone please tell me which version is *correct* w.r.t.

1. The latest ANSI-C draft.
2. Traditional behavior on UNIX compilers.

  thanks very much,
  
    Doug

Here's a complete program that illustrates the problem:

----------------------------------------
typedef struct
{
  int i;
  int j;
} bar;

#ifndef FIXBUG
static bar foo[4][4] =
{
  {1,0},  {2,0},  {3,0},  {4,0},  {5,0},  {6,0},  {7,0},  {8,0},
  {9,0}, {10,0}, {11,0}, {12,0}, {13,0}, {14,0}, {15,0}, {16,0},
};
#else
static bar foo[4][4] =
{
/* Note the extra { } for each row... */

  { {1,0},  {2,0},  {3,0},  {4,0},},
  { {5,0},  {6,0},  {7,0},  {8,0},},
  { {9,0}, {10,0}, {11,0}, {12,0},},
  {{13,0}, {14,0}, {15,0}, {16,0},},
};
#endif

main ()
{
  int i,j;
  
  for (i = 0;i < 4; i++)
    {
      for (j = 0; j < 4; j++)
        printf ("%4d", foo[i][j].i);
      printf ("\n");
    }
}

----------------------------------------


--
Any man's death diminishes me,              | schmidt at ics.uci.edu (ARPA)
Because I am involved in Mankind;           | office: (714) 856-4043
And therefore never send to know for whom the bell tolls;
It tolls for thee        -- John Donne



More information about the Comp.lang.c mailing list