【问题标题】:I want to access a general struct field inside another struct's field in C我想访问 C 中另一个结构字段中的通用结构字段
【发布时间】:2021-05-21 15:14:20
【问题描述】:

我有一个这样定义的结构:

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 个集合中的字符串 id。

我怎么能在 C 中做到这一点?

【问题讨论】:

    标签: c struct enums


    【解决方案1】:
    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;
    }
    

    【讨论】:

      【解决方案2】:

      您必须将内容数组设为 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;
      }
      
      

      并且不要让任何其他函数创建 comp 结构

      【讨论】:

        猜你喜欢
        • 2014-07-06
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2010-11-03
        • 2017-10-07
        • 1970-01-01
        相关资源
        最近更新 更多