2016-11-14 105 views
0

我有一个C语法问题,这让我疯狂。我已经定义了一些容器结构:C结构内动态数组内结构内的动态分配数组的语法

typedef struct AStruct { 
    int importantData1; 
    int importantData2; 
} A; 

typedef struct BStruct { 
    A* arr1;    // dynamic array of A structs 
} B; 

typedef struct CStruct { 
    B* arr2;    // dynamic array of B structs 
} C; 

正如你所猜测的,每个A结构体都保存着我程序的一部分数据。每个B结构都包含一个A的数组,每个C结构包含一个B的数组。我预计只需要一个C结构。我的C结构数据,以便总量将是:

total data in C == (num of B's) * (num of A's) 

棘手的部分是,我不知道有多少A和B的我需要在编译的时候。这意味着我不能硬连线阵列大小;他们必须动态分配。

有一种方法可以做到这一点。这里是我的笨拙尝试:

void makeContainers(C* x, int numB, int numA){ 
    x->arr2 = (B*)malloc(numB * sizeof(B)); // allocate an array of empty B structs 
    B* Bptr; 
    int i; 
    for(i=0; i<numB; i++){ 
      Bptr = x->arr2[i];      // Bptr is one of the B's in C's arr2 
      Bptr = (A*)malloc(numA * sizeof(A)); // Allocate an array of empty A stucts 
    } 
} 

int main() { 
    C* bigContainer = (C*)malloc(sizeof(C)); // Allocate the C struct 
    makeContainers(bigContainer, 8, 8);   // populate C with B's and A's 

    return 0; 
} 

这在纸上看起来很棒...但是编译器恨Bptr = x->arr2[i];线。 (在Linux上使用GCC编译)这里的错误:

[Linux]$ gcc -Wall setsInSets.c 
setsInSets.c: In function ‘makeContainers’: 
setsInSets.c:23:8: error: incompatible types when assigning to type ‘struct B *’ from type ‘B’ 
    Bptr = x->arr2[i]; // Bptr is one of the B's in C's arr2 
     ^

的 “从型B型结构乙” 部分混淆了我。不知道编译器在这里告诉我什么。

而且...这是有点儿一个C 101型的问题,但我不能肯定我完全明白什么makeContainers第一行()是做:

x->arr2 = (B*)malloc(numB * sizeof(B)); 

在这里,我分配内存对于一系列B结构......但这是否意味着当这个命令结束时,我实际上有一堆“空的”B结构准备好了吗?或者我只是放下内存,但内存本身只包含“垃圾”?换句话说,我是否必须走x->arr2阵列和malloc()单个B结构?

我知道这可能是一个重复的问题 - 但我仍然要求它,因为我认为这个问题的“动态数组结构内的结构”是一个非常具体的问题。

谢谢! -Pete

+0

'x-> arr2 [i]'评估为一个'B'对象,而不是一个指针。也许你打算写'Bptr = x-> arr2'? – Jezor

+1

[不要在C中投入malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar

+0

那些根本不是数组。它们是结构体,所以你不能做'x-> arr2 [i]'但是如果你想访问,例如'importantData1',你实际上可以做'x-> arr2-> arr1-> importantData1' –

回答

3

x->arr2是指针到B结构

x->arr2[i]被解除引用一个元件阵列中即乙结构

要设置所需的结构的地址的指针阵列

B* Bptr = &(x->arry[i]); 

,或者更方便

B* Bptr = x->arry + i; 

我建议你在你的结构中写入数组的大小,它可能会在稍后派上用场。

例如

typedef struct BStruct { 
    size_t elements;  // to know how many A structs 
    A* arr1; 
} B; 

编辑:

代码

Bptr = x->arr2 + i;   // Bptr is one of the B's in C's arr2 
Bptr = malloc(numA * sizeof(A)); 

的这部分是没有意义的,首先要将Bptr,然后将其分配到另一个地址。

+0

这非常非常清楚,谢谢。我的语法现在可用。将大小添加到结构中是一种天才,我已经实现了它。太好了! – Pete