我正在做一些C編程並且遇到了一個問題,我沒有做很多C編程,所以它可能是一些愚蠢的東西,原諒我,然後但我就是想不通爲什麼這個代碼塊取決於如果我執行行//puts("is_in_group called");
或不給予不同的輸出C代碼給出了不同的返回值,這取決於「puts(」..「)的用法
GHashTable *is_in_group(GPtrArray *groups, char *city, int elements_in_groups){
//puts("is_in_group called"); If I uncomment this line, the function works, but otherwise it doesn't
GHashTable *temp_set = NULL;
for (int i = 0; i < elements_in_groups; i++){
temp_set = g_ptr_array_index(groups, i);
if(g_hash_table_contains(temp_set, city)){
printf("Found: %s\n",city);
return temp_set;
}
}
printf("City: %s not found\n", city);
return temp_set;
}
輸出,//puts("is_in_group called");
:。
Added:
Wheeling
Sumter
----
is_in_group called
Found: Wheeling
is_in_group called
Found: Sumter
輸出而不puts("is_in_group called")
;
Added:
Wheeling
Sumter
----
City: Wheeling not found
City: Sumter not found
如果我移動我的放置/打印,我可以得到輸出的其他組合,例如找到一個而不是一個。
完整的代碼在這裏,但我不希望任何人看它。整個解析器()部分是100%,所以沒有錯。 http://pastebin.com/spcxMF76 這裏是如何的功能是:
/*runs kruskal's algorithm on @param edges and stores
a minimal spanning tree in @param min_tree*/
void run_kruskal(Edge edges[], GPtrArray *result)
{
int elements_in_groups = 0;
GPtrArray *groups = g_ptr_array_new();
for (int i = 0; i < 1; i++)
{
char *city_a = edges[0].city_a;
char *city_b = edges[1000].city_b;
// Check if city A and B are already in a group
GHashTable *t1 = g_hash_table_new (NULL, compare_strings);
g_hash_table_add(t1, city_a);
g_ptr_array_add (groups, t1);
elements_in_groups++;
GHashTable *t2 = g_hash_table_new (NULL, compare_strings);
g_hash_table_add(t2, city_b);
g_ptr_array_add (groups, t2);
elements_in_groups++;
GHashTable *group_A = is_in_group(groups, city_a, elements_in_groups);
GHashTable *group_B = is_in_group(groups, city_b, elements_in_groups);
}
}
由於代碼中存在錯誤,它看起來像是在調用未定義的行爲。我會建議檢查你的'g_ptr_array_index()'和'g_hash_table_contains()'函數是否有錯誤,例如緩衝區溢出或未初始化的變量。 – 2014-11-04 16:23:18
你確定兩個構建/運行之間的唯一區別是該行的評論嗎?沒有其他代碼被更改?沒有不同的編譯標誌?沒有輸入是不同的?沒有外部資源被修改? – 2014-11-04 16:27:17
@squeamishossifrage是的,一定是這樣的,但仍然無法弄清楚這條線會如何影響。這些函數來自GLIB庫,這是相當好用的,所以懷疑這可能是一個錯誤。 – Jakkra 2014-11-04 16:32:54