c++ - 我倒数第二个值是垃圾,程序是关于计算总和
问题描述
#include <iostream>
using namespace std;
int main()
{
int oldsize;
string choice;
cout << "Welcome to the Walmart Calculation Center!";
cout << endl;
cout << "Enter the Number of Items" << endl;
cin >> oldsize;
int* items = new int[oldsize];
for (int i = 0; i < oldsize; i++)
{
cout << "ENTER THE PRICE OF ITEM" << i + 1 << "!" << endl;
cin >> items[i];
}
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice == "YES")
{
int newbie;
int newsize;
int total = 0;
while (choice == "YES")
{
newsize = oldsize + 1;
int* Nitems = new int[newsize];
for (int i = 0; i < oldsize; i++)
{
Nitems[i] = items[i];
}
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
Nitems[oldsize] = newbie;
oldsize = newsize;
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice=="NO")
{
for (int i = 0; i < newsize; i++)
{
cout << Nitems[i] << endl;
}
}
}
}
}
这个程序是关于在商店计算账单的总和。并询问用户是否要输入任何其他项目,直到他/她说不。最后它显示总账单。
解决方案
你永远不会改变items
数组,但你会改变oldsize
代表它的大小的变量。当您尝试从 to 复制项目items
时Nitems
,您会超出items
数组的范围(因为oldsize
大于数组的实际大小)。
最简单的解决方法是在更改大小的同时重新items
指向。Nitems
while (choice == "YES")
{
newsize = oldsize + 1;
int* Nitems = new int[newsize];
for (int i = 0; i < oldsize; i++)
{
Nitems[i] = items[i];
}
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
Nitems[oldsize] = newbie;
oldsize = newsize;
items = Nitems; //here
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice=="NO")
{
for (int i = 0; i < newsize; i++)
{
cout << Nitems[i] << endl;
}
}
}
看到标有注释的行了吗?它使items
指针指向与 相同的数组Nitems
。不涉及复制,如果您更改items[1]
,Nitems[1]
将看到相同的更改。但是有两个指向同一个数组的指针可以让您在下一次迭代中创建新数组时保留当前数组。
内存泄漏当然存在问题,但在您学会如何正确管理内存之前不要太担心。放置不当delete
比内存泄漏更糟糕(尤其是在这样的小程序中)。
当然,如果您使用以下代码,您的代码会简单得多std::vector
:
std::vector<int> items;
while (choice == "YES")
{
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
items.push_back(newbie);
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice=="NO")
{
for (int i = 0; i < items.size(); i++)
{
cout << items[i] << endl;
}
}
}
推荐阅读
- memory-management - 运行时错误:CUDA 内存不足。试图分配...但内存是空的
- java - 需要将 Arraylist 从 java 程序传递给 R 脚本作为参数
- amazon-web-services - 是否可以在 AWS Application Load Balancer 中启用 x-forward
- python - ModuleNotFoundError:没有名为“keras”的模块无法导入 keras
- javascript - Bootstrap 3 datetimepicker - MinTime 和 MaxTime
- bash - bash函数内的花括号
- react-native - 反应原生避免滚动视图/平面列表在键盘打开时缩小
- google-cloud-platform - Google API Gateway:在标头中提供 API 密钥
- cmake - 未指定 target_include_directories 的 CMake 构建目标
- visual-studio - Blazor 和 Visual Studio 的 Intellisense - 一些 Blazor 组件引用显示为错误错误,直到您单击文件