I'm beginning at coding in C++, and I recently encountered a problem that I can't really find a solution for it, because I don't understand my error.
My program is made to give the conversion in Kelvin to Celsius, but it isn't able to do it for more than 3 temperatures in a row. As soon as I pass 4, it gives me the right conversion with a memory problem (out of range?).
Error in "xxx": Double free or corruption (out): 0x0000000001c94c40
And when I enter more than four temperatures it gives some random numbers, that are probably values of other adresses.
Here is my program.
#include <iostream>
using namespace std;
unsigned int NumberT {0}; //Definition of the global variables
double* Kelvin=new double[NumberT];
double* Celsius=new double[NumberT];
unsigned int i=0;
double* Conversion (double, double, unsigned int) //Conversion function
{
for(unsigned int i=0;i<NumberT;++i)
{
Celsius[i]=Kelvin[i]-273.15;
}
return Celsius;
}
void printTemperatures (double, double, unsigned int) //Print function
{
for(unsigned int i=0;i<NumberT;++i)
{
cout<<"The temperature is "<< Kelvin[i] <<" [K], which is "<< Celsius[i] <<" [C]"<<endl;
}
return;
}
int main () //Main
{
cout<<"How many temperatures do you want to enter?"<<"\n";
cin>>NumberT;
cout<<"What are the temperatures?"<<"\n";
for (unsigned int i=0;i<NumberT;++i)
{
cin>>Kelvin[i];
}
Conversion (Kelvin[i], Celsius[i], NumberT);
printTemperatures (Kelvin[i], Celsius[i], NumberT);
delete [] Celsius;
delete [] Kelvin;
return 0;
}
So I would be really happy to know what is wrong with my code, and why is it like this. I heard that we shouldn't use global variables, and this can maybe help me to understand why.
By the way I'm interested to have some advices on how to write a proper code with a good syntax, without having scope problems. Because I would like to learn how to write a function that is the most "universal" possible, so that I can pull it and use it in another program with other variables.
Thank you in advance for your support
P.S.: I'm using g++ as compiler and the 2011 C++ standard