Home > database >  C lang Multidimensional arrays
C lang Multidimensional arrays

Time:04-19

just started playing with C, I have this

char str_arr[2][3] = {"gou", "ram"};
printf("%s / %s / %s", str_arr, str_arr[0], str_arr[1]);

which prints:

gouram / gouram / ram

and

char str_arr[2][4] = {"gou", "ram"};
printf("%s / %s / %s", str_arr, str_arr[0], str_arr[1]);

prints:

gou / gou / ram

I really don't understand, the 4 is the maximum size, yet makes no sense at all.

CodePudding user response:

Passing str_arr to the function printf with the %s format specifier will invoke undefined behavior. The %s specifier requires a char * as an argument. The expression str_arr is not a char * and will also not decay into one. However, writing str_arr[0] instead of str_arr will decay to a char *.

In the first example

char str_arr[2][3] = {"gou", "ram"};

passing str_arr[0] will also invoke undefined behavior, for a different reason:

The %s format specifier as a function argument a pointer to a valid string, i.e. a pointer to a sequence of characters terminated by a null character. However, neither str_arr[0] nor str_arr[1] are terminated by a null character, because there is no room for one.

However, when you write

char str_arr[2][4] = {"gou", "ram"};

there is room for a terminating null character, and both str_arr[0] and str_arr[1] will have one after initialization, so the behavior of the programm is well-defined when passing these sub-arrays to the function printf (i.e. there is no undefined behavior).

  • Related