![](/img/trans.png)
[英]In C if a variable is not assigned a value then why does it take garbage value?
[英]Allocated memory does not take value it is assigned
我一直在這個論壇上搜索了幾個小時,試圖找到我的問題的答案,閱讀了手冊頁,但似乎看不到我在做什么。
這就是正在發生的事情。 我有一個程序,如果兩個對象之間的距離足夠小,它將循環遍歷並將條目添加到(圖形)鄰接矩陣。 如果它們不夠小而不能添加到鄰接矩陣中,如果它們又不太大,則應將條目的坐標添加到稱為“ possible_edgelist”的坐標對列表中。
我的問題是“ possible_edgelist”沒有采用我為其分配的值(i和j為其條目0和1)。 但是,正在執行分配兩側的兩個命令。 我將在代碼后粘貼一些示例輸出:
uncertain_edge_max = 4;
certain_edge_max = 3.2;
printmatrix(shelldistmtx, shellsize, shellsize); //this is being generated correctly.
max_num_of_edges = shellsize*(shellsize-1)/2;
possible_edgelist=(int**)malloc(max_num_of_edges* sizeof(int*));
for(i=0; i<max_num_of_edges; i++)
{
possible_edgelist[i] = (int*)malloc(2 * sizeof(int));
}
poss_edge_num = 0;
for(i=0; i<shellsize; i++)
{
adjacency_matrix[i][i]=0;
for(j=i+1; j<shellsize; j++)
{
if (shelldistmtx[i][j]<=certain_edge_max) {
adjacency_matrix[i][j]= 1;
adjacency_matrix[j][i]= 1;
}
else
{
if(shelldistmtx[i][j] <= uncertain_edge_max)
{
printf("%d \t %d \t %d \t %lf \n", poss_edge_num, i, j, shelldistmtx[i][j]);
// ^this is being executed
//*****THESE TWO LINES ARE NOT BEING EXECUTED???*********
possible_edgelist[poss_edge_num][0]=i;
possible_edgelist[poss_edge_num][1]=j;
poss_edge_num=poss_edge_num + 1; //this is being executed
}
adjacency_matrix[i][j] = 0;
adjacency_matrix[j][i] = 0;
}
}
adjacency_matrix[i][shellsize] = 1;
adjacency_matrix[shellsize][i] = 1;
}
//troubleshooting output
for (i=0; i<poss_edge_num; i++)
{
printf("%d, %d \n", possible_edgelist[poss_edge_num][0], possible_edgelist[poss_edge_num][1]); //this outputs zeros and bizarre numbers.
}
現在,對於輸出,我得到:
0.000000 3.535534 3.535534 4.960403 4.960403
3.535534 0.000000 5.000000 3.715589 3.715589
3.535534 5.000000 0.000000 3.715589 3.715589
4.960403 3.715589 3.715589 0.000000 3.400000
4.960403 3.715589 3.715589 3.400000 0.000000
0 0 1 3.535534
1 0 2 3.535534
2 1 3 3.715589
3 1 4 3.715589
4 2 3 3.715589
5 2 4 3.715589
6 3 4 3.400000
0, -1073741824
0, -1073741824
0, -1073741824
0, -1073741824
0, -1073741824
0, -1073741824
0, -1073741824
最后一組值應該是(0,1),(0,2),(1,3)等。我不知道為什么未正確分配這些值,有人可以解釋一下這里發生了什么嗎?
我唯一想到的就是這種情況發生在一個快速連續被多次調用的函數中,但是我確信在返回之前,free()隨每個函數調用而變化的所有內容都將在這里被釋放(以及不變,已在函數外部分配/釋放)。
哦,是的,我也嘗試過calloc()。 除了全0以外,其他問題相同。
救命!
您的打印forl循環有錯誤:
for (i=0; i<poss_edge_num; i++)
{
printf("%d, %d \n", possible_edgelist[i][0], possible_edgelist[i][1]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.