繁体   English   中英

在C中分配多维数组

[英]Assigning multidimensional array in C

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

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_value; 基本上等同于使用memcpy(test, &init_value, sizeof(*test)); 或嵌套循环,您可以在其中复制test->matrix的各个元素。

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

TestStruct *Clone(const TestStruct *mat) {

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

    if (test)
        *test = *mat;

    return test;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM