gpt4 book ai didi

c++ - 输出二维字符串数组时出现段错误

转载 作者:行者123 更新时间:2023-11-28 06:00:50 25 4
gpt4 key购买 nike

所以我一直在研究这段代码,我不是很熟练。我创建了两个类,一个为购物 list 定义一个项目,另一个创建一个对象数组并将它们作为列表输出。该程序在我的 Windows 命令提示符下运行,但当我使用 cout 语句输出数组时,在 GNU 命令行上出现段错误。

void List::createList(Item ** itemPtr, int size)
{
string** list1 = new string*[size];
for(int i = 0; i < 5; i++)
{
list1[i] = new string[5];
}
for (int i = 0; i < size; i++)
{
list1[i][0] = itemPtr[i]->getName();
list1[i][1] = itemPtr[i]->getUnit();
list1[i][2] = itemPtr[i]->getSTRnumToBuy();
list1[i][3] = itemPtr[i]->getSTRcost();
list1[i][4] = itemPtr[i]->getSTRextCost();
}
cout << endl << left << fixed << setw(15) << setprecision(2) << "Name";
cout << fixed << left << setw(15) << setprecision(2) << "Unit Type";
cout << fixed << left << setw(15) << setprecision(2) << "# of units";
cout << fixed << left << setw(15) << setprecision(2) << "Cost/Unit";
cout << fixed << left << setw(15) << setprecision(2) << "Total" << endl;

for (int i = 0; i < size; i++)
{
cout << fixed << left << setw(15) <<setprecision(2)<<endl<< list1[i][0];
cout << fixed << left << setw(15) << setprecision(2) << list1[i][1];
cout << fixed << left << setw(15) << setprecision(2) << list1[i][2];
cout << fixed << left << setw(15) << setprecision(2) << list1[i][3];
cout << fixed << left << setw(15) << setprecision(2) << list1[i][4];
}
}

最佳答案

你的第一个循环应该是:

for(int i = 0; i < size; i++)
{
list1[i] = new string[5];
}

也就是说,循环直到 size,而不是 5。

关于c++ - 输出二维字符串数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com