1

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;
5
  • You should catch exceptions by reference to avoid slicing. Commented Mar 22, 2015 at 23:05
  • You have two different variables called ptrTemperatures. Commented Mar 22, 2015 at 23:25
  • I've rolled back your recent changes, as, by removing the original problem, you made the existing answers incorrect. If you have more problems, please ask a new question. Commented Mar 22, 2015 at 23:56
  • @SimonMᶜKenzie, sorry, I'll ask a new question Commented Mar 23, 2015 at 0:00
  • Your variables dayCount and dayNumber are confusing. You're storing the count of days in dayNumber, but the current day number in dayCount. Commented Mar 23, 2015 at 0:10

2 Answers 2

2

You should change your allocation as follows:

try
{
   ptrTemperatures = new double[dayNumber];
}
Sign up to request clarification or add additional context in comments.

1 Comment

This fixed the random crashing. Thanks
0

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.

1 Comment

I get what you mean, the visual below helped me realize what you meant. Thanks for the help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.