簡體   English   中英

我想訪問 C 中另一個結構字段內的通用結構字段

[英]I want to access a general struct field inside another struct's field in C

我有一個這樣定義的結構:

typedef struct {
    char id[20];
    char descrizione[250];
    char tipoSet[30];
    int scatoleDisponibili;
    float costo;
} Set;

我有另一個名為 Complex 的結構,我想要一個字段來存儲一個僅包含 Set 結構 ID 的數組。

typedef struct {
    char idComplesso[20];
    content[10];
    int dimLogica;
} complex;

所以,我希望內容數組(最大大小為 10)能夠存儲最大為 10 Set 的字符串 id。

我怎么能在 C 中做到這一點?

typedef struct {
    char id[20];
    char descrizione[250];
    char tipoSet[30];
    int scatoleDisponibili;
    float costo;
} Set;

typedef struct {
    char idComplesso[20];
    int dimLogica;
    size_t nsets;
    char *content[];
} complex;
complex *assign(Set *s, size_t nsets)
{
    complex *cml = malloc(sizeof(*cml) + nsets * sizeof(cml -> content[0]));

    /* allocation check */

    cml -> nsets = nsets;
    for(size_t i = 0; i < nsets; i++)
    {
        cml -> content[i] = s[i].id;
    }
    return cml;
}

您必須將內容數組設置為 char* 數組,並且在創建結構時僅接受來自 Set 結構的 id。 像這樣的東西:

complex* createComplex(Set* sets) {
  complex* comp = (complex*)malloc(sizeof(complex));
  for (int i=0; i<10; i++) {
    comp->content[i] = sets[i].id;
  }
  return comp;
}

並且不要讓任何其他 function 創建 comp 結構

暫無
暫無

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

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