0

在一些使用指针和引用的新领域中,我试图通过引用将数组传递给使用指针的函数,但是无论我尝试什么,我都会遇到错误,我确信问题很容易解决,但我只是我似乎无法理解它,任何人都可以看到我犯的错误吗?任何帮助都会有很大帮助,谢谢

#include<iostream>
#include<cmath>
#include <iomanip>
#include <cstdio>   
#include <cstdlib>
#include <new>

using namespace std;

//Inline function 
inline double getFahrenheit(double theCelsius)
{ 
//Convert the celcius to farenheit   
return (theCelsius + 32) * 5 / 9;  
}

void outputWeather(double *temperaturesArray, const string WEEK_DAY_NAMES[], const     double MAX_NUMBER)
{
     //this is a counter that will increment through the days and various 
     int counter;
     //reset the counter to 0 so we can use it again       
     counter = 0;
     //print a header       
     cout << "THIS WEEKS TEMPERATURE REPORT " << endl;
     //print a divider 
     cout << "=============================" << endl;
     //while the counter is less than 7 repeat again
     while(counter < MAX_NUMBER)
     {
         //print out the temperatures by day          
         cout << WEEK_DAY_NAMES[counter] << "     " << temperaturesArray[counter] << "\370C    " << getFahrenheit(temperaturesArray[counter]) <<"\370F    "<< endl;
         //increase the counter by 1
         counter +=1;  
     }
}

//Function that will determine whether or not the value the user entered was numeric     and within the range
double checkValidation(string weekDay)
{
 //Create a variable to store a valid number
 double validNumber;

 //This will hold the value for the lowest  
 const double MIN_NUMBER = 1;
 //This will hold the value for the highest temperature
 const double MAX_NUMBER = 365;
 //This will hold the value for the valid number that the user will eventually enter 
 validNumber = 0.0;

 //This will alert the user to enter a temperature for that day of the week
 cout << "Please enter the temperature for " << weekDay << endl;
 //This will take in teh value the user entered for teh temperature 
 cin >> validNumber; 

     //If the text the user entered was not numeric start again             
 if(cin.fail())            
 {
     //C++ built in methods for clearing the cin                     
     cin.clear();              
     fflush(stdin);

     //alert the user what they typed was wrong 
     cout << "invalid input. please try again and enter a numeric value" << endl; 
     //pass in the weekeday and start over
     checkValidation(weekDay);                     
 } 
 else 
 {
     //if teh number falls outside the range
     if(validNumber < MIN_NUMBER || validNumber > MAX_NUMBER)
     {
         //Alert the user that it was outside the range           
         cout << "invalid input. please try again and enter a value between -90 and 60" << endl; 
         //pass in the weekday and try again          
         checkValidation(weekDay);
     }

 }
 //return the valid number    
 return validNumber;  

}


int main()
{
    //this is a counter that will increment through the days and various 
    int counter;
    //a constant to hold the variable for the number of days
    const int MAX_COUNTER = 7;
    //an array that will hold all the days of the week
    const string WEEK_DAY_NAMES[] = 
    { 
          "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 
    };

    //this will hold all of teh temperatures
    double temperaturesArray[MAX_COUNTER]; 
    //start the counter off at 0      
    counter = 0; 

    //begin telling the user to enter temperatures by printing a header
    cout << "Please enter the temperature for every day of the week " << endl;
    //while the counter is less than 7 we will repeat
    while(counter < MAX_COUNTER)
    {                                                       
    //add temperature to the array 
    temperaturesArray[counter] = checkValidation(WEEK_DAY_NAMES[counter]); 
    //add 1 to the counter            
    counter +=1;                     

    }

    double * arrayPointer = new double[MAX_COUNTER];

    arrayPointer = &temperaturesArray;

    outputWeather(arrayPointer, WEEK_DAY_NAMES, MAX_COUNTER);       

system("PAUSE");
return 0;              
}
4

2 回答 2

5

In C++, the size of an array is encoded into its type.

There is no general "array of doubles" type. But there is an "array of 7 doubles" type, and an "array of 13 doubles" type, and so on.

So to pass an array as an array, and not simply as a pointer, to a function, you need to encode the precise type in the function's signature.

It won't be "a function which takes an array", but "a function which takes an array of size 7".

The way to do that is as follows:

void f(double (&arr)[7]);

Or of course, you can template it, if the array size is not fixed:

template <size_t N>
void f(double (&arr)[N]);

But really, what you're trying to do shouldn't be done using raw arrays at all.

Use the standard library vector.

于 2013-03-24T17:57:47.587 回答
0

简而言之,更换线路

arrayPointer = &temperaturesArray;

arrayPointer = temperaturesArray;

使代码编译。

请注意,它arrayPointer是类型double*并且temperaturesArray是类型double[MAX_COUNTER](with MAX_COUNTER = 7)。因此,您可以分配arrayPointer给 a 的地址,double但不能分配arrayPointer给 a 的地址double[MAX_COUNTER]。这就是原始代码试图做的事情,因此无法编译。

另一方面, a 的每个元素double[MAX_COUNTER]都是 a double。特别是,第一个元素是 a double,您可以将其地址分配给arrayPointer

arrayPointer = &temperaturesArray[0];

上面的修复只是这条线的一个合体糖。实际上,当您将“类型 T 的数组”(例如double[MAX_COUNTER])类型的对象分配给“类型 T 的指针”时,编译器会执行所谓的数组到指针的转换,这意味着分配第一个的地址数组元素指向指针。

现在对您的代码(使用提供的修复)做一点评论,特别是以下几行:

double * arrayPointer = new double[MAX_COUNTER];
arrayPointer = temperaturesArray;

MAX_COUNTER上面的第一行分配堆内存来存储类型对象的数组double。然后将该数组的第一个元素的地址分配给arrayPointer

然后,以下行重新分配arrayPointer给 的第一个元素的地址temperaturesArray。因此,堆分配数组的第一个元素的地址丢失了,您不能再使用delete它了。请记住,每次调用都new必须与调用匹配delete(否则您会出现内存泄漏)。但是,在这种特殊情况下,最好不要调用delete. 实际上,您应该消除对的调用,new因为堆内存从未使用过。更准确地说,您可以删除上面的第一行。

于 2013-03-24T18:04:05.390 回答