簡體   English   中英

是否可以將指針傳遞給C中的結構?

[英]Is it possible to pass pointers to a struct in C?

我從main調用函數init_latent_variables並將指針傳遞給SAMPLE類型的結構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); 
}

以下是功能定義。 內存分配在此函數中工作正常,但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語言中這樣做嗎?

更新 :不確定之前出了什么問題。 清理並重新編譯似乎可行。 多謝您的寶貴時間致歉。 已經標記了該問題,以便主持人可以將其刪除。

在分配sample->examples之前,您要取消引用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.");       
}

考慮使用calloc()代替malloc,或使用memset在使用結構之前將其清除為0。

首先,您必須分配示例SAMPLE結構的成員……據我所知,它必須是一個對象數組……而且,當然,在C中沒有引用,只有“值”或“指針”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM