2013-10-10 84 views
1

嗨我的頭文件中有一個數組對象。C++段錯誤錯誤

private: 
Customer** customerListArray; 

然後在我的CPP文件I設置數組大小,並添加對象,如下圖所示

void AppManager::createArrays(vector<vector<string> > data) { 

    customerListArray = new Customer* [data.size()]; 

    for (unsigned int i = 0; i < data.size(); i++){ 

     try { 

      Customer* cust = createCustomerObject(data[i]); 
      customerListArray[i] = cust; 
     } 
     catch(string err) { 

      cout << "Error processing line '" << i << "' of data file. Error Message : " << err << "\n"; 
     } 
    } 
} 

數據載體的尺寸是約14000項。然而,當我通過customerListArray和打印項目環我碰到下面的錯誤,

C5545 - Burton G. Craft - 3/1/14 
C5546 - Zena F. Wallace - 10/2/14 
C5547 - Ursa P. Orr - 20/4/14 
C5548 - Adara X. Rogers - 3/6/13 
C5549 - Carter L. Newman - 15/1/14 
C5550 - Maxwell V. Watkins - 5/6/13 
C5551 - Ria V. Morrow - 8/12/12 
C5552 - Kirk Z. Hines - 27/4/14 
C5553 - Brent L. Bentley - 13/10/13 
C5554 - Thane W. Cobb - 8/8/14 
C5555 - Serina M. Macias - 13/8/13 
C5556 - Maryam J. Lynch - 1/6/13 
C5557 - Breanna M. Lewis - 20/10/13 
Segmentation fault 

它總是崩潰在項目C5557段故障。當我使用矢量時,它工作得很好。但我的要求是通過賦值使用數組。

請指教:)

謝謝。

編輯:

vector<vector<string> > data= fileReader(customerFile); 
data= customerVals.size(); //about 14000 records 

//debug priting 
for (unsigned int i = 0; i < numOfCustomers; i++) { 
     Customer* cust = customerListArray[i]; 
     cout << cust->getCustomerId() << " - " << cust->getName() << " - " << cust->getDateLastPurchased()->getDay() << "/" << cust->getDateLastPurchased()->getMonth() << "/" << cust->getDateLastPurchased()->getYear() << "\n"; 
} 
+0

什麼是'data.size()',當程序崩潰時什麼是'i'?添加幾張照片。 – kevintodisco

+1

可能需要顯示用於打印的循環 - 畢竟它是發生崩潰的地方。 – DrC

+0

打印之前您是否正在檢查'NULL'? –

回答

0

do'h!我忘了檢查null,非常感謝,元素5558永遠不會因爲異常而被添加到數組中,因此它是空的!

for (unsigned int i = 0; i < numOfCustomers; i++) { 

     Customer* cust = customerListArray[i]; 
     if(cust != NULL) { 

      cout << cust->getCustomerId() << " - " << cust->getName() << " - " << cust->getDateLastPurchased()->getDay() << "/" << cust->getDateLastPurchased()->getMonth() << "/" << cust->getDateLastPurchased()->getYear() << "\n"; 
     } 
    } 

檢查NULL是否解決了問題!

+0

這是版本還是調試版本?我期望在發佈版本中,如果發生異常,指針將被初始化並且有一些垃圾值。它不會是NULL,但也不會指向有效的對象。我認爲你應該在'catch'塊中明確地將它設置爲NULL。 – danadam

+0

會做謝謝:) –