2016-03-31 75 views
0

我想用C语言创建一个渲染表函数,可能是最差的语言。C三维数组初始化

我有一个小问题,初始化一个表是一个字符串的二维数组,它使它成为一个三维数组。

我不能初始化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[][][]和所有可能的变体与* ....

+3

该阵列除第一个之外的尺寸必须是固定的(指定)。使用'char * table [] [3]',或者'char table [] [3] [7];'。 –

+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] 
+0

我喜欢C99'复合字面'的方式,很好的把戏!谢谢 ! –

0
下面

见代码:

char *first[] = { "hello", "my", "friend" }; 
char *second[] = { "hihi", "haha", "hoho" }; 
char **table[] = { first, second, NULL };