2013-11-21 36 views
0

我知道我必須忽略簡單的事情。我有一個程序,讓用戶通過顯示每個探針的索引來觀察不同的搜索算法如何探測數組。我有一個傳遞給排序算法函數的指針,並且它應該被賦予搜索到的編號所在的索引號。然後指針在另一個函數中使用,以顯示找到哪個索引值(如果找到)。 (C - 指向數組索引號的指針

我在函數中得到運行時錯誤,顯示找到該值的索引。(search_results)(當搜索到的數字不在數組中時,程序運行良好)它必須是一個簡單的錯誤,但我認爲一組新的眼睛可能會有所幫助。

一切都是int,除了found_status其是char

這裏是主()的代碼。 (必需的東西)

int *p_return_index = NULL; 

/* Fill arrays with data           */ 
fill_array(seq_data, max_index); 
fill_array(prob_data, max_index); 
fill_array(bin_data, max_index); 

while(printf("\n\n\nEnter an integer search target (0 to quit): "), 
     scanf("%d", &searched_number), searched_number != 0) 
{ 
    printf("\n\n"); 
    printf("\nOrdered Sequential Search:"); 
    show_data(seq_data, max_index, searched_number); 
    if(ordered_seq_search(seq_data, max_index, searched_number, p_return_index) == 1) 
    { 
     found_status = 'S'; 
     search_results(found_status, p_return_index); 
    } 
    else 
    { 
     found_status = 'U'; 
     search_results(found_status, p_return_index); 
    } 

這是指針傳遞給指定索引的地方。

int ordered_seq_search(int array[], int max_index, int searched_number, int *p_return_index) 
{ 
int index = 0; 

printf("\n Search Path: "); 
while (index < max_index && searched_number != array[index] && 
     searched_number > array[index]) 
{ 
    printf("[%2d]", index); 
    index++; 
} 

if(searched_number == array[index] != 0) 
{ 
    p_return_index = &index; 
    return 1; 
} 
else 
    return 0; 
} 

這就是錯誤發生的地方。

void search_results(char found, int *p_return_index) 
{ 
printf("\nSearch Outcome: "); 
if(found == 'S') 
    printf("Successful - target found at index [%2d]", *p_return_index); 
      //I get the error at the line above. 
if(found == 'U') 
    printf("Unsuccessful - target not found"); 
if(found != 'S' && found != 'U') 
    printf("Undetermined"); 
return; 
} 

如果有人能找出什麼是錯的,那對我來說會是一個很大的幫助。如果您需要更多信息,請發表評論,我會盡快回復。

回答

1

p_return_index用NULL初始化。

使用int p_return_index[1];

比search_results(...)

if(searched_number == array[index] != 0) { 
    *p_return_index = index; 
+0

它的工作!謝謝您的幫助。 –

1
if(searched_number == array[index] != 0) { 
    p_return_index = &index; 

應該

if(searched_number == array[index] != 0) { 
    *p_return_index = index; 

您的代碼設置本地指針指向一個局部變量的地址;此更改不適用於調用代碼。如果您要影響調用代碼,則需要更新p_return_index指向的內存。

這將我們帶入下一個問題。

int *p_return_index = NULL; 

應該

int return_index; 

讓你記憶mainordered_seq_search寫入。

+1

隨着'INT return_index;',它看起來像'如果找到匹配return_index'只用於隨後,但也許初始化它_something_可能會使調試一致。對於我的錢,我會把它size_t並用SIZE_MAX初始化它。 – chux