如何返回动态分配的数组?

时间:2014-04-23 23:12:49

标签: c++ arrays

因此,对于我的问题,我需要一个动态分配的数组,该数组将在main函数中创建并填充在另一个函数中。我遇到的问题是我需要在其他函数中使用该数组,并且在我的函数中填充它之后我的数组没有任何值(或者至少这似乎是这种情况)这是我的代码:< / p>

#include <iostream>
#include <iomanip>
using namespace std;

//prototypes
int getNumber();
void getMovieData(int *ptrToArray, int arraySize);
void sort(int *ptrToArray, int arraySize);
double getAverage(int *ptrToArray, int arraySize);
void print(int *ptrToArray, int arraySize);

int main()
{
    int stuNum = 0;
    int* stuArray;
    stuArray = new int[stuNum];

    getMovieData(stuArray, stuNum);

    cout << "--- Here is the data you entered ---" << endl;
    print(stuArray, stuNum);

    sort(stuArray, stuNum);
    cout << "--- Here is the data you entered sorted ---" << endl;
    print(stuArray, stuNum);

    cout << fixed << setprecision(2);
    cout << "Here is the average of your survey" << getAverage(stuArray, stuNum) << endl;


    system("pause");
    return 0;
}

int getNumber()
{
    int userNum;
    cin >> userNum;
    while (userNum <= 0)
    {
        cout << "Error number must be greater than zero." << endl;
        cin >> userNum;
    }
    return userNum;
}

void getMovieData(int *ptrToArray, int arraySize)
{
    cout << "Enter the number of students being surveyed: ";
    arraySize = getNumber();
    for (int i = 0; i < arraySize; i++)
    {
        cout << "Enter the movies seen by Student " << i + 1 << ": ";
        ptrToArray[i] = getNumber();
    }
    return;
}

void sort(int *ptrToArray, int arraySize)
{
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < arraySize - 1; j++)
        {
            if (ptrToArray[j] > ptrToArray[j + 1])
            {
                int temp = ptrToArray[j];
                ptrToArray[j] = ptrToArray[j + 1];
                ptrToArray[j + 1] = temp;
            }
        }
    }
}

double getAverage(int *ptrToArray, int arraySize)
{
    int total = 0;
    for (int i = 0; i < arraySize; i++) { total = total + ptrToArray[i]; }
    return total;
}

void print(int *ptrToArray, int arraySize)
{
    for (int i = 0; i < arraySize; i++) { cout << ptrToArray[i] << "\t"; }
    cout << endl;
}

1 个答案:

答案 0 :(得分:4)

您正在分配一个零元素的数组。将stuNum的值更改为表示所需数量的正数。