如何在C中声明一个常量2d字符串数组

时间:2015-03-23 08:28:22

标签: c arrays string

我有以下数组结构:

left , right , top
top , left , right 
top , top , left 

我想在C中声明它,我已经这样做了:

char *movements[][] = {{"left","right","top"},
                        {"top","left","right"},
                        {"top","top","top"}
                       }

但我得到了这个error : array has incomplete element type. 实现这一目标的正确方法是什么(声明和访问(打印))。我是否需要采用三维数组?

2 个答案:

答案 0 :(得分:7)

在C中,您必须在定义二维数组时指定列大小。看看这个问题:Why do we need to specify the column size when passing a 2D array as a parameter?

char *movements[][3] = {
                           {"left","right","top"},
                           {"top","left","right"},
                           {"top","top","top"}
                       };

答案 1 :(得分:-1)

在C中声明结构有多种方法。 在你的特定情况下,我会声明一个3×3矩阵的形式

char *movements[3][3] = {
                          {"left","right","top"  },
                          {"top" ,"left" ,"right"},
                          {"top" ,"top"  ,"top"  }
                        };

但是,如果您不知道数组的初始大小并希望在函数内填充数组,则可以声明它

更新:

char ***movements;

并将其作为参数传递给您的函数,然后您可以为其分配内存并填充它(请参阅下面的示例)。你只需要记住以后解除分配: - )

这是一个矢量的例子;

void SomeFunction(char ***ptr_movements){
    int dim = 3;
    **ptr_movements = (char*) malloc(dim*sizeof(char*));

    (*ptr_movements)[0] = "left"; (*ptr_movements)[1] = "right"; (*ptr_movements)[2] = "top";
}

void main(){
    char **movements;
    SomeFunction(&movements);
    // Do something with resulting array
}