[英]C Syntax for a dynamic-allocated array within a struct within a dynam array within a struct
我有一個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輸入結構B ”部分使我感到困惑。 不知道編譯器試圖在這里告訴我什么。
另外...這有點像C 101類型的問題,但是我不確定我是否完全了解makeContainers()的第一行在做什么:
x->arr2 = (B*)malloc(numB * sizeof(B));
在這里,我正在為B個結構的數組分配內存...但這是否意味着當該命令完成時,我確實准備好了一個“空” B結構的數組? 還是我只是預留了內存,但內存本身僅包含“垃圾”? 換句話說,我是否必須遍歷x->arr2
數組並malloc()
一個單獨的B結構?
我知道這可能是一個重復的問題-但無論如何我都會提出這個問題,因為我認為這個問題的“動態數組內的結構中的動態數組內的結構”的性質非常具體。
謝謝! -皮特
x->arr2
是指向B結構數組的指針
x->arr2[i]
正在解引用數組中的一個元素,即B結構
要設置指針,您需要結構的地址
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,然后將其分配給另一個地址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.