【问题标题】:How to declare a constant 2d string array in C如何在 C 中声明一个常量二维字符串数组
【发布时间】:2015-05-26 04:25:14
【问题描述】:

我有以下数组结构:

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. 实现这一点的正确方法是什么(声明和访问(打印))。我必须采用三维数组吗?

【问题讨论】:

    标签: c arrays string


    【解决方案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
    }
    

    【讨论】:

    • char *movements[][] 无效,如问题中所述。此外,“需要记住事后释放它”在没有代码的情况下会令人困惑。
    • 是的,谢谢,我很快就完成了,因此我更新了我的答案。但是,我似乎无法在最后找到释放内存的正确方法; free(movements) 只是给我一个无效的指针错误。
    【解决方案2】:

    在 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"}
                           };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 2011-04-18
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多