通过指针数组排序

Sorting through array of pointers

本文关键字:数组排序 指针      更新时间:2023-10-16

当我尝试在函数sortArray中显示考试成绩时,我只能访问内存地址。我如何访问分数的值??sortArray函数整体正确吗?

#include <iostream>
using namespace std;
void sortArray(int *[], int);
int main()
{
    int *testScores = nullptr;
    //dynamically allocate an array
    int scoreNUMS;
    int score;

    cout << "Please enter the total number of test scores" << endl;
    cin >> scoreNUMS;
    testScores = new int[scoreNUMS];
    //dynamically allocates an array large enough to hold scoreNUMS
    for(int i = 1; i <= scoreNUMS; i++)
    {
        cout << "Enter student " << i << "'s test score" << endl;
        cin >> score;
        if (score <= -1)
        {
            cout << "Please enter positive numbers only!" << endl;
        }
        *(testScores + i) = score;
        //puts the input score in the array

    }
    sortArray(&testScores, scoreNUMS);
    return 0;
}

我不确定下面的函数是否正确,因为我不知道在哪里放置*和&

void sortArray(int *array[], int size)
{
    bool swap;
    int temp;
    do
    {
        swap = false;
        for(int count = 0;count < (size - 1); count++)
        {
            if(array[count] > array[count + 1])
            {
                temp = *array[count];
                array[count] = array[count + 1];
                array[count + 1] = &temp;
                swap = true;
            }
        }
    }while(swap);
    for(int i = 0; i < size; i++)
    cout << *(array + 1) << endl;
}

错误:数组包含scoreNUMS元素,第一个是testScores[0] -第一个索引为零。最后一个索引是scoreNUMS-1

你必须写

for(int i = 0; i < scoreNUMS; i++)

PS:你可以使用下一个原型:

void sortArray(int [], int);

UPD:通过传递指向数组第一个元素的指针来将数组传递给函数。(当你将数组传递给函数时,它不会被复制)

并以这种方式运行函数:sortArray(testScores, scoreNUMS);