簡體   English   中英

具有嵌套結構的動態數組

[英]Dynamic array with nested structs

我正在嘗試使用嵌套結構構建動態數組。 當插入一個項目時,我得到以下信息。 錯誤:從“結構B *”類型分配給“結構B”類型時,類型不兼容

問題是什么,我在哪里做錯。 請幫忙。

typedef struct {
   size_t used;
   size_t size;

   struct B {
      int *record1;
      int *record2; 
   } *b;

} A;


void insertArray(A *a, int element) {
  struct B* b =  (struct B*)malloc(sizeof(struct B));
  A->b[element] =  b;
}

問題在於Ab 不是 struct的數組,而是一個指針 您可以使指針指向struct數組,但默認情況下不這樣做。

最簡單的方法是malloc正確數量的struct B s轉換Ab開頭,然后把的副本struct B沒錯成陣列。

void initWithSize(struct A *a, size_t size) {
    a->size = size;
    a->b = malloc(sizeof(struct B) * size);
}

void insertArray(A *a, int index, struct B element) {
    assert(index < a->size); // Otherwise it's an error
    // There's no need to malloc b, because the required memory
    // has already been put in place by the malloc of initWithSize
    a->b[index] = element;
}

稍微復雜一點的方法是使用C99的靈活數組成員 ,但是將struct A組織成自己的數組的任務會復雜得多。

void insertArray(A *a, int element) {
        struct B b ;
        b.record1 = 100;
        b.record2 = 200;
        A->b[element] =  b;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM