gpt4 book ai didi

c++ - 动态数组分配随机崩溃

转载 作者:行者123 更新时间:2023-11-30 03:55:08 28 4
gpt4 key购买 nike

我一直在努力学习指针和在运行时分配空间。我决定将我的一项旧作业(天气温度数组)更改为动态分配的数组。我想我快完成了,但每次我运行它并输入温度时,我的程序都会在没有警告的情况下崩溃。我想了解它崩溃的原因。

int dayNumber;
double fahrenheit = 0;
double cTemperature = 0;
const double MAXIMUM_TEMPERATURE = 60;// constants for mix/max
const double MINIMUM_TEMPERATURE = -90 ;
const int MAXIMUM_DAYS = 365;
const int MINIMUM_DAYS = 1;
double *ptrTemperatures;

cout << "How many days would you like to enter? ";
dayNumber = myValidation::GetValidInteger(MINIMUM_DAYS, MAXIMUM_DAYS);
try
{
double *ptrTemperatures = new double[dayNumber];
}
catch(exception e)
{
cout << "Failed to allocate memory: " << e.what() << endl;
}
cout << "\n\nTEMPERATURE REPORTER\n____________________________\n Please Enter the temperature for each day.";

for(int dayCount = 0; dayCount < dayNumber; dayCount++){
cout << "Celsius Temperature for Day " << (dayCount + 1) << ": ";
ptrTemperatures[dayCount] = myValidation::GetValidDouble(MINIMUM_TEMPERATURE, MAXIMUM_TEMPERATURE);
}





delete[] ptrTemperatures;
return 0;

最佳答案

您应该按如下方式更改您的分配:

try
{
ptrTemperatures = new double[dayNumber];
}

关于c++ - 动态数组分配随机崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200786/

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