2017-03-05 81 views
0

我希望我沒有過分簡化我的代碼,但我基本上試圖做的是在容器中查找元素的存在,並將指針返回給它。指針訪問有問題嗎?

我有結構如

typedef struct INHs{ 
    int ID; 
} INHs; 

typedef struct sub_container{ 
    INHs** list_inh; 
    int nb_list; 
} sub_container; 

typedef struct container { 
    sub_container* cont; 
    int nb_elem; 
} container; 

然後在我的主要方法,我有分配一個容器(我會離開它爲簡單起見,和給定的ID;而現在我不會遍歷子容器找到我的目標INHs結構)。

INHs** test_INH = NULL; 
INHs** return_val = NULL; 

int ID = 10; 

container* cont; //allocated on all memory 

for (uint n=0; !test_INH && n<container_nb_elem; n++){ 

    return_val = find_ptr(&cont[n], ID, &test_INH); 

} 


INHs** find_ptr(sub_container* sub_cont, int ID, INHs*** test){ 

    INHs** res = NULL; 

    for (uint i=0; !res && i<sub_cont->nb_list; i++){ 

     if (sub_cont->list_inh[i].ID == ID) { 

     (*test) = &(sub_cont->list_inh[i]); 
     res = &(sub_cont->list_inh[i]); 
     } 

    return res; 
} 

我知道我並不需要都返回值來我的元素,另外一個作爲函數參數,但這些我都試過了兩個版本。我不知道我在做什麼錯,但valgrind崩潰告訴我,「test_INH」或「result_val」是未初始化的,儘管我將它們設置爲null。

有人看到我在這裏失蹤了嗎?

+1

我認爲這可能是相關的,看你如何分配你的結構 –

+0

也許顯示我們的確切的錯誤。 – nbro

+1

注意:C不支持_methods_。你應該使用調試器。 – Olaf

回答

1
typedef struct INHs{ 
    int id; 
} INHs; 

typedef struct sub_container{ 
    INHs **ptrs; 
    int nb_list; 
} sub_container; 

typedef struct container { 
    sub_container *items; 
    int nb_elem; 
} container; 

int main(void) 
{ 
INHs **found = NULL; 
int id = 10; 
container *cont; //allocated on all memory 

for (uint n=0; n < cont->nb_elem; n++){ 
    found = find_ptr(&cont->items[n], id); 
    if (found) break; /* found it! */ 
    } 

if(found) { 
     /* do something useful with *found ... */ 
     } 
return 0; 
} 

INHs **find_ptr(sub_container *sub_cont, int id) 
{ 

for (uint i=0; i < sub_cont->nb_list; i++){ 
    if (sub_cont->ptrs[i]->id != id) continue; 
    return &sub_cont->ptrs[i]; 
    } 

return NULL; 
} 

BTW:我發現指針數組一個integer結構很奇怪。 這些結構是否都是單獨的malloc()?

+0

很可能(或者至少我們可以假裝它是)1整數結構是MCVE創建過程的一個假象。 –

+0

@JonathanLeffler同意。它確實可能是一些異構的項目。或者指向其他結構。 – wildplasser