简体   繁体   English

如何在结构内部的结构成员上获取指针

[英]How to get pointer on a struct member inside a struct

My struct are like this : 我的结构是这样的:

typedef struct Bounds Bounds;
struct Bounds
{
    int type;
    double lb;
    double ub;
};

typedef struct HelperGlpk HelperGlpk;
struct HelperGlpk
{
    double *matrix_coefs;
    double *obj_coefs;
    Bounds *row_bounds;
    Bounds *col_bounds;
    int *column_of_coef;
    int *row_of_coef;
    int cpt_coef;
    int cpt_contrainte;
};

I initiliaze them that way (on my main) : 我以这种方式初始化它们(在我的主机上):

HelperGlpk helper_glpk;

    helper_glpk.matrix_coefs = malloc((nbr_coefs + 1) * sizeof(double));
    helper_glpk.matrix_coefs[0] = 0;

    helper_glpk.obj_coefs = malloc((nbr_colums + 1) * sizeof(double));
    helper_glpk.obj_coefs[0] = 0;

    helper_glpk.column_of_coef = malloc((nbr_colums + 1) * sizeof(int));
    helper_glpk.column_of_coef[0] = 0;

    helper_glpk.row_of_coef = malloc((nbr_rows + 1) * sizeof(int)); 
    helper_glpk.row_of_coef[0] = 0;

    helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds));
    helper_glpk.row_bounds = malloc((nbr_rows + 1) * sizeof(Bounds));

    helper_glpk.cpt_coef = 1;
    helper_glpk.cpt_contrainte = 1;

Then, inside the function genere_contrainte_1() that I call this way : genere_contrainte_1(i, j, &helper_glpk, baie); 然后,在我以这种方式调用的函数genere_contrainte_1()中: genere_contrainte_1(i, j, &helper_glpk, baie);

I want to access to the pointer helper_glpk->col_bounds[helper_glpk->cpt_coef]->type but I got this error : 我想访问指针helper_glpk->col_bounds[helper_glpk->cpt_coef]->type但是出现此错误:

error: invalid type argument of ‘->’ (have ‘Bounds {aka struct Bounds}’)
  helper_glpk->col_bounds[helper_glpk->cpt_coef]->type = GLP_DB;

Could you tell me what am I doing wrong ? 你能告诉我我在做什么错吗?

Edit : I DO want to access the pointer to ->type, because .type doesn't "save" the value for use outside the function genere_contrainte_1() 编辑:我确实想访问指向-> type的指针,因为.type不会“保存”在函数genere_contrainte_1()之外使用的值。

The col_bounds member of the HelperGlpk structure is being used as an array. HelperGlpk结构的col_bounds成员被用作数组。 Which is to say that 就是说

helper_glpk->col_bounds[helper_glpk->cpt_coef]

is an instance of the Bounds structure, not a pointer to a Bounds structure. 是的一个实例Bounds结构,而不是一个指向Bounds结构。

Hence, the correct syntax uses the dot notation 因此,正确的语法使用点符号

helper_glpk->col_bounds[helper_glpk->cpt_coef].type = GLP_DB;

helper_glpk->col_bounds evaluates to a Bounds* . helper_glpk->col_bounds计算结果为Bounds*

helper_glpk->col_bounds[helper_glpk->cpt_coef] evaluates to a Bounds . helper_glpk->col_bounds[helper_glpk->cpt_coef]计算为Bounds

Hence, you need to use: 因此,您需要使用:

helper_glpk->col_bounds[helper_glpk->cpt_coef].type = GLP_DB;
                                           // ^^ Use . not ->

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM