我一直试图在运行时学习指针和分配空间。我决定将我的一个旧任务,一个气候温度数组更改为一个动态分配的数组。我想我已接近完成,但每次运行它并输入温度我的程序都会在没有任何警告的情况下崩溃。我想知道它崩溃的原因。
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;
答案 0 :(得分:2)
您应该按如下方式更改分配:
try
{
ptrTemperatures = new double[dayNumber];
}
答案 1 :(得分:0)
您在ptrTemperatures
子句中声明了一个名为try
的新变量。这是你要分配的那个。 try
之外的变量仍然未分配且未初始化,因此您正在访问随机内存。