除了第一阵列的尺寸必须是固定的(指定的)。使用char *table[][3]
,或者char table[][3][7]
:
#include <stdio.h>
int main(void)
{
char *table1[][3] =
{
{ "hello", "my", "friend" },
{ "hihi", "haha", "hoho"},
};
char table2[][3][7] =
{
{ "hello", "my", "friend" },
{ "hihi", "haha", "hoho"},
};
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
printf("[%d][%d] = [%s]\n", i, j, table1[i][j]);
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
printf("[%d][%d] = [%s]\n", i, j, table2[i][j]);
return 0;
}
输出:
[0][0] = [hello]
[0][1] = [my]
[0][2] = [friend]
[1][0] = [hihi]
[1][1] = [haha]
[1][2] = [hoho]
[0][0] = [hello]
[0][1] = [my]
[0][2] = [friend]
[1][0] = [hihi]
[1][1] = [haha]
[1][2] = [hoho]
还有其他的方法来做到这一点,如使用C99 '复合文字':
#include <stdio.h>
int main(void)
{
char **table3[] =
{
(char *[]){ "hello", "my", "friend" },
(char *[]){ "hihi", "haha", "hoho" },
NULL,
};
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
printf("[%d][%d] = [%s]\n", i, j, table3[i][j]);
return 0;
}
输出:
[0][0] = [hello]
[0][1] = [my]
[0][2] = [friend]
[1][0] = [hihi]
[1][1] = [haha]
[1][2] = [hoho]
该阵列除第一个之外的尺寸必须是固定的(指定)。使用'char * table [] [3]',或者'char table [] [3] [7];'。 –
编译器自己无法计算它太糟糕了,它不会那么难。感谢您的帮助。 –