C语言中多维数组的赋值

C语言中多维数组的赋值,c,arrays,memory-management,C,Arrays,Memory Management,我试图将多维数组分配给结构中的统一数组,如下所示: typedef struct TestStruct { int matrix[10][10]; } TestStruct; TestStruct *Init(void) { TestStruct *test = malloc(sizeof(TestStruct)); test->matrix = {{1, 2, 3}, {4, 5, 6}}; return test; } 我得到了下一个错误: t

我试图将多维数组分配给结构中的统一数组,如下所示:

typedef struct TestStruct
{
    int matrix[10][10];

} TestStruct;

TestStruct *Init(void)
{
    TestStruct *test = malloc(sizeof(TestStruct));

    test->matrix = {{1, 2, 3}, {4, 5, 6}};

    return test;
}
我得到了下一个错误:

test.c:14:17: error: expected expression before '{' token
  test->matrix = {{1, 2, 3}, {4, 5, 6}};

在C语言中,分配矩阵的最佳方法是什么

不能以这种方式初始化矩阵。在C99中,您可以执行以下操作:

*test = (TestStruct){{{1, 2, 3}, {4, 5, 6}}};
在C99之前,您将使用本地结构:

TestStruct *Init(void) {
    static TestStruct init_value = {{{1, 2, 3}, {4, 5, 6}}};

    TestStruct *test = malloc(sizeof(TestStruct));

    if (test)
        *test = init_value;

    return test;
}
注意,结构赋值*test=init_值;实质上等同于使用memcpytest、&init_值、sizeof*test;或者是一个嵌套循环,您可以在其中复制test->matrix的各个元素

您还可以通过以下方式克隆现有矩阵:

TestStruct *Clone(const TestStruct *mat) {

    TestStruct *test = malloc(sizeof(TestStruct));

    if (test)
        *test = *mat;

    return test;
}

但是我想在Init函数中初始化矩阵,有没有办法通过指针来初始化呢?@JacobLutin:上面描述的各种方法都会初始化矩阵。有没有一种方法可以通过指针来实现这一点?数组不能用C语言赋值。它们可以初始化,但这只能通过定义来实现。