Array decay and multidimensional arrays

suggest change

An array converts to a pointer to its first element in most expressions. Only the outermost array type is removed:

Array type Type after conversion
char[20] char *
char[4][20] char (*)[20]
char *[4] char **
char[3][4][20] char (*)[4][20]
char (*[4])[20] char (**)[20]

Therefore, a two-dimensional character array cannot be passed to a function expecting char **:

#include <stdio.h>

void print_strings(size_t count, char strings[][20])
{
    for (size_t index = 0; index < count; ++index) {
        puts(strings[index]);
    }
}

int main(void)
{
    char strings[4][20] = {
        "Example 1", "Example 2", "Example 3", "Example 4"
    };
    print_strings(4, strings);
}

The adjusted parameter type is char (*)[20], a pointer to one 20-character row.

When the row width is known only at run time and VLA types are supported, pass it before the array parameter:

void print_strings(size_t count, size_t width,
                   char strings[count][width]);

An int ** or char ** instead describes a pointer to a pointer. It is suitable for an array of pointers, whose rows may be separate allocations, but not for a contiguous array of arrays.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents