1

main関数から呼び出して、型init_latent_variablesの構造体へのポインタを渡していますsampleSAMPLE

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); 
}

以下は関数定義です。この関数ではメモリ割り当ては正常に機能しますが、元の変数はmain変更されません。

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.");       
}

構造体の定義は次のとおりです。

typedef struct latent_var {
  int *h_is;
} LATENT_VAR;

typedef struct example {
  LATENT_VAR h;
} EXAMPLE;

typedef struct sample {
  EXAMPLE *examples;
} SAMPLE;

ポインタを構造体に渡すのは正しいですか。Cでそれを行うことは可能ですか?

更新:以前に何が問題だったのかわかりません。クリーンして再コンパイルするとうまくいくようです。時間を無駄にしてしまったことに感謝し、お詫び申し上げます。モデレーターが削除できるように、すでに質問にフラグを立てています。

4

2 に答える 2

0

sample->examples割り当てる前に逆参照しています:

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.");       
}

これは次のようになります。

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.");       
}

malloc の代わりに calloc() の使用を検討するか、memset を使用して構造体を使用する前に 0 にクリアしてください。

于 2012-08-19T14:09:33.950 に答える
0

まず、SAMPLE 構造の例のメンバーを割り当てる必要があります...私が理解しているように、それはオブジェクトの配列でなければなりません...そしてもちろん、C には参照はなく、「値」または「ポインター」のみです。

于 2012-08-19T14:09:40.827 に答える