简体   繁体   中英

How can I fill a structure with the values of an identical structure within a function?

Okay so here's my problem:

1) I have a structure defined say like this:

struct minos_model
{
  int ifanis, ifdeck, npts, icb, cmb, noc;
  double tref;
  double r[MODEL_NPTS_MAX], rho[MODEL_NPTS_MAX], vpv[MODEL_NPTS_MAX],     vsv[MODEL_NPTS_MAX],
  qk[MODEL_NPTS_MAX], qmu[MODEL_NPTS_MAX], vph[MODEL_NPTS_MAX],     vsh[MODEL_NPTS_MAX], eta[MODEL_NPTS_MAX];
  char model_name[MODEL_LINE_LEN];
};
typedef struct minos_model model_t;

2) I have declared some structures of this form:

/* Declare structures */
model_t candidate_mod, current_mod, empty_mod;

3) I then pass them into a function declared as something like this:

void
perturb_model( model_t *candidate_mod, model_t *current_mod, model_t *empty_mod )
{
    candidate_mod = current_mod; // *THIS LINE*
    <various other functions and whatnot>
}

4) I then call the function like so:

perturb_model( &candidate_mod, &current_mod, &empty_mod );
// arguments passed as pointers

So the above is a simplified version of what I've done. I am trying (on line marked THIS LINE in step 3) to set candidate_mod to a different structure (current_mod), I would use a loop but one, this seems inelegant, two, sometimes the structure I am setting it equal too (current_mod) contains fewer values (than candidate_mod) and as such I am worried the excess values from the original structure (candidate_mod) would remain.

I should also mention, since perhaps it's relevant, that the function is defined in a separate c file linked in the makefile, so perhaps there is a difficulty with sharing globals.. but I think passing the pointer as an argument should solve this?

Also, it seems from my research that perhaps the use of extern might help, though I cannot figure out how after many attempts.

If someone could explain the best way to do this I would be extremely grateful!! I know how to do it trivially in my main code but the structures have to be assigned like this within the function.

Cheers.

只是将src的值放入dest中,不要分配指针...但是您的真正需求并不清楚。

*candidate_mod = *current_mod;

You are passing an address of the structure. When you say candidate_mod = current_mod; you are assigning the address of current_mod to candidate_mod which is not correct. You have to dereference that structure using code like this

*candidate_mod = *current_mod;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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