简体   繁体   English

动态数组分配随机崩溃

[英]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. 您在try子句中声明了一个名为ptrTemperatures的新变量。 This is the one you're allocating. 这是您要分配的那个。 The variable outside the try remains unallocated and uninitialized, so you are accessing random memory. try之外的变量保持未分配和未初始化状态,因此您正在访问随机存储器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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