2012-03-20 223 views
0

這是我正在爲類進行的任務。長話短說,我試圖調用main中的allocate()函數來執行。我不斷收到testArray未在此範圍內聲明的錯誤。「我有點困惑,如果我的返回語句是通過我的函數調用的,而不是如何在範圍內調用?我希望這是有道理的,我很困惑我用這些指針和功能。任何建議表示讚賞,感謝。'testArray未在此範圍內聲明'

#include <iostream> 
using namespace std; 

int* allocate(int&); 

int* allocate(int &numOfScores) 
{ 

    int *testArray; 

    //prompt user for scores 
    cout << "How many test scores would\n"; 
    cout << "you like to process: " << endl; 
    cin >> numOfScores; 

    //dynammically allocate an arrray to hold the scores 
    testArray = new int[numOfScores]; 

    //get the scores from user 
    for(int count = 0; count < numOfScores; count++) 
    { 
     cout << "Enter Score: " << endl; 
     cin >> testArray[count]; 
    } 


    //release the memory that was allocated for *ptr 
    delete [] testArray; 
    testArray = 0; 

    return testArray; 
} 

int main() 
{ 

    allocate(testArray); 

    return 0; 

} 
+0

我明白了!謝謝大家的建議,我想因爲我正在調用allocate()函數,它會返回而不管範圍,我現在明白了,謝謝。 – Gmenfan83 2012-03-20 23:40:38

回答

1

這是因爲你指的testArray好像它是在目前的功能是什麼,你真正需要的定義是

#include <iostream> 
using namespace std; 

int* allocate(int&); 

int* allocate(int &numOfScores) 
{ 

    int *testArray; 

    //prompt user for scores 
    cout << "How many test scores would\n"; 
    cout << "you like to process: " << endl; 
    cin >> numOfScores; 

    //dynammically allocate an arrray to hold the scores 
    testArray = new int[numOfScores]; 

    //get the scores from user 
    for(int count = 0; count < numOfScores; count++) 
    { 
     cout << "Enter Score: " << endl; 
     cin >> testArray[count]; 
    } 


    //release the memory that was allocated for *ptr 
    delete [] testArray; 
    testArray = 0; 

    return testArray; 
} 

int main() 
{ 
    int* testArray; 
    int numberOfScores; 
    testArray=allocate(numberOfScores); 
    delete[] testArray; 
    return 0; 
} 

不過,我會勸阻這種編碼風格,你應該考慮使用std :: vectors。

例如

size_t nun_scores; 
std::cin >> nun_scores; 
std::vector<int> scores(num_scores); 
//so on 

http://en.cppreference.com/w/cpp/container/vector

+0

不在'allocate'內調用'delete [] testArray'釋放數組的內存?然後你要返回一個指向未分配空間的指針,這個空間有未定義的行爲......對吧? – Mosby 2012-03-21 00:35:55

+0

@Mosby:如果指針被解引用,它只會變成未定義的行爲。 – Mankarse 2012-03-21 01:02:40

2

testArray是內部allocate一個局部變量,並且不存在,並且是不內部main可見。如果你想創建內部main一個局部變量將被分配的allocate的返回值,你會做這種方式:

int numberOfScores; 
int* testArray = allocate(numberOfScores); 

但意識到,既然你有delete[]編內allocate數組,並設置爲0,您在main中創建的testArray將指向NULL。您最好不要在allocatedelete[]內部將其設置爲0,而是在main的末尾,而不是在allocate的內部,或者如果可以,請使用std::vector以避免必須執行手動內存管理。

此外,您可能希望確保cin >> numOfScores沒有失敗,而且如果成功,numOfScores大於0

1

要調用與您從未創建過一個變量testArray的分配()函數。在另一個函數(即範圍)中可能存在一個相同名稱的變量並不重要 - 它不在main()中,也不在全局中。