2016-07-31 85 views
2

我试图分配多维数组unitilized阵列中的结构是这样的:分配多维数组用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的最佳方式分配矩阵?

+0

数组不能用C语言来分配它们可以被初始化,但是这仅* *可以在定义中完成。 – alk

回答

4

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

注意结构assignent *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; 
} 
+0

但我想Init()函数初始化矩阵,有没有办法通过指针? – JacobLutin

+1

@JacobLutin:上面介绍的各种方法**可以**初始化矩阵。你的意思是什么?有没有办法通过指针来做到这一点?* – chqrlie