Before C99, you had to define the inner arrays separately:
#include <stdio.h>
int main() {
const char *array_0[] = { "car", "toy", "game" };
const char *array_1[] = { "go", "play", "read" };
const char **array[] = { array_0, array_1 };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%s ", array[i][j]);
}
printf("\n");
}
return 0;
}
With C99, you can now define and initialize the same object directly:
#include <stdio.h>
int main() {
const char **array[] = {
(const char *[]){ "car", "toy", "game" },
(const char *[]){ "go", "play", "read" },
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%s ", array[i][j]);
}
printf("\n");
}
return 0;
}
Of course this is more flexible than a 2D matrix: each inner array can have a different size, as in:
#include <stdio.h>
int main() {
const char **array[] = {
(const char *[]){ "car", "toy", "game", NULL },
(const char *[]){ "go", "play", NULL },
(const char *[]){ "read", NULL },
NULL,
};
for (int i = 0; array[i]; i++) {
for (int j = 0; array[i][j]; j++) {
printf("%s ", array[i][j]);
}
printf("\n");
}
return 0;
}
Output:
car toy game
go play
read
Note that I added the const
keyword because string literals should not be modified, so pointers to them should be defined as const char *
.