简体   繁体   中英

Dynamic Array Allocation Random Crashing

I've been trying to learn about pointers and allocating space during runtime. I decided to change one of my older assignments, a weather temperature array into a dynamically allocated array. I think I am close to being done but everytime I run it and enter a temperature my program crashes with no warning. I want to understand why it is crashing.

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;

You should change your allocation as follows:

try
{
   ptrTemperatures = new double[dayNumber];
}

You're declaring a new variable called ptrTemperatures inside your try clause. This is the one you're allocating. The variable outside the try remains unallocated and uninitialized, so you are accessing random memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM