简体   繁体   中英

Is it possible to pass pointers to a struct in C?

I am calling from main the function init_latent_variables and passing pointer to a struct sample of type SAMPLE

int main(){
    SAMPLE sample;
    sample = read_struct_examples();
    init_latent_variables(&sample);
    return 0;
}

SAMPLE read_struct_examples() {
    SAMPLE sample;        
    sample.examples = (EXAMPLE *) malloc(1*sizeof(EXAMPLE));
    if(!sample.examples) die("Memory error.");
    return(sample); 
}

Following is function definition. The memory allocation works fine in this function, but the original variable in main remains unchanged.

void init_latent_variables(SAMPLE *sample) {
    sample->examples[0].h.h_is = (int *) malloc(5*sizeof(int));
    if(!sample->examples[0].h.h_is) die("Memory error.");       
}

Following are the struct definitions:

typedef struct latent_var {
  int *h_is;
} LATENT_VAR;

typedef struct example {
  LATENT_VAR h;
} EXAMPLE;

typedef struct sample {
  EXAMPLE *examples;
} SAMPLE;

Am I right in passing a pointer to struct. Is it possible to do so in C?

UPDATE : Not sure what was wrong earlier. Clean and recompile seems to work. Thanks and apologies for wasting your time. Already flagged the question so that moderators could delete it.

You're dereferenceing sample->examples before you allocate it:

void init_latent_variables(SAMPLE *sample) {
    sample->examples[0].h.h_is = (int *) malloc(5*sizeof(int));
    if(!sample->examples[0].h.h_is) die("Memory error.");       
}

this should be :

void init_latent_variables(SAMPLE *sample, int num_examples) {
    sample->examples = (EXAMPLE *) malloc(sizeof EXAMPLE * num_examples);
    if(!sample->examples) die("Memory error.");   
    sample->examples[0].h.h_is = (int *) malloc(5*sizeof(int));
    if(!sample->examples[0].h.h_is) die("Memory error.");       
}

Consider using calloc() instead of malloc, or use memset to clear your structs to 0 before using them.

首先,您必须分配示例SAMPLE结构的成员……据我所知,它必须是一个对象数组……而且,当然,在C中没有引用,只有“值”或“指针”。

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