2012-09-17 76 views
2

我在將數據傳遞給一個函數後,出現了一個數組垃圾的問題。這是將它傳遞給只打印出來的函數的正確方法嗎?傳遞數組通過引用

while(infile){ 
     infile >> batch; 
     infile >> amount; 
     cout << batch << "  " << amount<< endl; 
     totalChocolates[batch-1]+=amount; 
     chocolateBatches[batch-1]++; 

    } 

    //header(); 
    print(totalChocolates,chocolateBatches); 

    system("pause"); 
    return 0; 

void print(int *total,int *batch) 
{ 
    for(int i = 0;i<size;i++) 
    { 
     cout << i+1 << "  " << batch[i] << "  " << total[i] << endl; 

    } 
} 

好吧,我拿出了功能,我仍然是垃圾。

while(infile>> batch >> amount){ 
     //infile >> batch; 
     //infile >> amount; 
     cout << batch << "  " << amount<< endl; 
     totalChocolates[batch-1]+=amount; 
     chocolateBatches[batch-1]++; 

    } 
    for(int i = 0;i<size;i++) 
    { 
     cout << i+1 << "  " << chocolateBatches[i] << "  " << totalChocolates[i] << endl; 

    } 

它返回

1  64 
8  907 
18  1133 
9  636 
3  1134 
16  1101 
6  313 
7  791 
7  1130 
1  1221 
20  332 
22  697 
6  807 
2  36 
2  747 
16  1219 
3  859 
18  639 
18  312 
7  1079 
10  1074 
5  678 
18  59 
1  -858993418  -858960818 
2  -858993429  -858971910 
3  -858993421  -858963346 
4  -858993431  -858970692 
5  -858993427  -858963901 
6  -858993416  -858961011 
7  -858993417  -858960812 
8  -858993421  -858961874 
9  -858993417  -858960079 
10  -858993418  -858960161 
11  -858993422  -858963562 
12  -858993428  -858970812 
13  -858993460  -858993460 
14  -858993427  -858967859 
15  -858993422  -858964267 
16  -858993418  -858954549 
17  -858993423  -858966453 
18  -858993423  -858964725 
19  -858993460  -858993460 
20  -858993433  -858973375 
21  -858993419  -858963644 
22  -858993426  -858968664 
23  -858993456  -858993060 
24  -858993460  -858993460 
25  -858993455  -858990222 
Press any key to continue . . . 
+6

錯,錯,錯。你絕不能讓輸入無人看守。 'infile >>批處理;'提供**否**保證閱讀'batch'是合法的。它應該是'while(infile >> batch >> amount){/ * ... * /}'。 –

+2

你如何確定'print'函數中的'size'? – Praetorian

+2

如果您使用的是C++,請使用'vector'。在C++中使用數組就像這樣的事情就像用錘子打開汽水罐。 – Dan

回答

3

好看多了,是的。問題是,你沒有正確地使用數組的大小,所以你可能只是在末尾跑進未初始化的空間。同時傳遞一個大小到print函數,所以你不會跑到最後。

編輯:雖然在你的問題評論中請注意Kerrek的警告。

+0

大小是一個const int我全局聲明 – Intelwalk

+0

但是你確定你讀取所有元素到'size'數組? – slugonamission

+0

是肯定的。 – Intelwalk