C如何创建二维字符数组?[duplicate]

kdfy810k  于 2022-12-03  发布在  其他
关注(0)|答案(3)|浏览(134)

此问题在此处已有答案

How should character arrays be used as strings?(4个答案)
9天前关闭。
所以我想创建一个二维数组的字符测试的目的。这里是我的代码。

const int rows = 4;
    const int columns = 6;
    //char field[rows][columns];
    //fill_field(rows,columns,field);
    char field[rows][columns] = {
                            "A BCD ",
                            "B CDA ", 
                            "C DAB ", 
                            "D ABC "
                            };

我得到错误说“可变大小的对象可能不会被初始化”和“多余的元素在数组初始化”的每一个字符串我已经键入。

zz2j4svz

zz2j4svz1#

For starters if you want that the array would contain strings then columns must be set to 7 . Otherwise the terminating zero character '\0' of the strings used as initializers will not be stored in the array. As a result the array will not contain strings.
This declaration

const int rows = 4;
const int columns = 6;
//char field[rows][columns];
//fill_field(rows,columns,field);
char field[rows][columns] = {
                        "A BCD ",
                        "B CDA ", 
                        "C DAB ", 
                        "D ABC "
                        };

declares a variable length array because the variables rows and columns are not integer constant expressions according the C Standard. From the C Standard (6.6 Constant expressions)
6 An integer constant expression117) shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.
and (6.7.6.2 Array declarators)
4 If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)
Such arrays may not be initialized in their declarations. From the C Standard (6.7.9 Initialization)
3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.
Instead you could write for example

enum { rows = 4, columns = 7 };
//char field[rows][columns];
//fill_field(rows,columns,field);
char field[rows][columns] = {
                        "A BCD ",
                        "B CDA ", 
                        "C DAB ", 
                        "D ABC "
                        };

Pay attention to that instead of the two-dimensional array you could declare an array of pointers to string literals like for example

const char * field[] = { "A BCD ", "B CDA ", "C DAB ", "D ABC " };

const size_t N = sizeof( field ) / sizeof( *field );

provided that you are not going to change the strings.
To access characters of the string literals you can use expressions with similar subscript operators as for two-dimensional arrays like for example

for ( size_t i = 0; i < N; i++ )
{
    for ( size_t j = 0; field[i][j] != '\0'; j++ )
    {
        putchar( field[i][j] );
    }
    putchar( '\n' );
}
4c8rllxm

4c8rllxm2#

如果大小不是**常量表达式 * a,则数组将变为可变长度数组(VLA),并且无法初始化此类对象。
const int不是常量表达式。
需要将变量定义更改为宏

#define rows 4
#define columns 6

https://godbolt.org/z/sYT8K8rva

ma8fv8wu

ma8fv8wu3#

有四种方式。选择你喜欢的语法...我刚刚编译了它们。

int main()
    {
        char field[4][6] = {
                               {'A',' ','B','C','D',' '},
                               {'B',' ','C','D','A',' '},
                               {'C',' ','D','A','B',' '},
                               {'D',' ','A','B','C',' '},
        };
    
        char fieldWithNulls[4][7] = {
                               {'A',' ','B','C','D',' ', 0},
                               {'B',' ','C','D','A',' ', 0},
                               {'C',' ','D','A','B',' ', 0},
                               {'D',' ','A','B','C',' ', 0},
        };

        char fieldWithNullsAndStrings[][7] = {
                          {"A BCD "},
                          {"B CDA "},
                          {"C DAB "},
                          {"D ABC "},
        };

       char fieldWithNullsAndStrings2[][7] = {
                      "A BCD ",
                      "B CDA ",
                      "C DAB ",
                      "D ABC ",
       };
    }

很明显,你可以根据自己的意愿来调整这些要求,这个问题并没有真正说明所有的要求是什么,只是说他正在做的事情不起作用。
您也可以删除第一个数组大小,因为编译器可以在给定列大小的情况下计算出它,例如:

char fieldWithNulls[][7] = {

最后三个数组包含一个零终止符,因此可以被视为c字符串。一旦编译,它们在内存中也是相同的。选择你喜欢的语法。

相关问题