【问题标题】:Assigning multidimensional array in C在 C 中分配多维数组
【发布时间】:2016-07-31 12:03:19
【问题描述】:

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

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 中分配矩阵的最佳方法是什么?

【问题讨论】:

  • 数组不能在 C 中赋值。它们可以被初始化,但这只能在定义时完成。

标签: c arrays memory-management


【解决方案1】:

您不能以这种方式初始化矩阵。在 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;
}

【讨论】:

  • 但是我想在 Init() 函数中初始化矩阵,有没有办法通过指针来完成?
  • @JacobLutin:上面描述的各种方法初始化矩阵。 有没有办法通过指针来做到这一点?
猜你喜欢
  • 2016-05-24
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2014-03-04
  • 1970-01-01
相关资源
最近更新 更多