1

嗨,我的头文件中有一个数组对象。

private:
Customer** customerListArray;

然后在我的 CPP 文件中,我设置数组大小并添加对象,如下所示,

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";
}
4

1 回答 1

0

做!我忘了检查空值,非常感谢,元素 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 修复了它的问题!

于 2013-10-10T23:12:56.860 回答