The two are only partly equivalent. The difference being that:
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
declares a two-dimensional array, which includes setting aside space for the array and ensuring that daytab
references that memory. However:
static char (*daytab)[13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
…only declares a pointer. So you’re trying to initialize a pointer with an array initializer, which doesn’t work as expected. There is no array; there’s no memory set aside for an array. What happens instead is that the first number in your initializer is assigned to the pointer daytab
, and the compiler generates a warning to let you know you’ve specified a lot of additional values that are just discarded. Since the first number in your initializer is 0
, you’re just setting daytab
to NULL
in a rather verbose way.
So if you want to do this sort of initialization, use the first version — it decays to the same pointer type that you explicitly declare in the second version, so you can use it the same way. The second version, with the array pointer, is needed when you wish to dynamically allocate the array or get a reference to another array that already exists.
So you can do this:
static char arr[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
static char (*ptr)[3] = NULL;
ptr = arr;
…and then use ptr
and arr
interchangeably. Or this:
static char (*ptr)[3] = NULL;
ptr = malloc(2 * sizeof(*ptr));
…to get a dynamically allocated 2-dimensional array (not an array of pointers to 1D arrays, but a real 2D array). Of course, it’s not initialized in that case.
The “equivalence” of the two variations just means that the 2D array, when it decays to a pointer to its first element, decays to the type of pointer declared in the second variation. Once the pointer version is actually pointed at an array, the two are equivalent. But the 2D array version sets up memory for the array, where the pointer declaration doesn’t… and the pointer can be assigned a new value (pointed at a different array) where the 2D array variable cannot.
In C99 you can do this, though (if not static
at least):
char (*daytab)[13] = (char [][13]){
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};