我想在C中创建一个渲染表函数,可能是最糟糕的语言。
我初始化一个表是一个二进制数组的字符串,这使得它成为一个char的三维数组。
我无法以这样的方式初始化tridimensionnal数组:
char *table[][] = {
{ "hello", "my", "friend" },
{ "hihi", "haha", "hoho"},
NULL
};
但是我收到了错误
test_table.c:8:11: error: array type has incomplete element type ‘char *[]’
char *table[][] = {
C编译器可以计算所有维度的长度吗?
我也尝试将其声明为table[][][]
以及*
所有可能的变种....
答案 0 :(得分:1)
除第一个之外的数组维度必须是固定的(指定的)。使用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]
答案 1 :(得分:0)
见下面的代码:
Id