通过指针数组排序
Sorting through array of pointers
当我尝试在函数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);
相关文章:
- 数组的指针从不分段故障
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- 显示错误输出的简单数组排序程序
- 如何使用非类型模板参数传入指向数组的指针
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- C++ 指向枚举数组的指针
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 从指向结构数组的指针中提取元素
- 为什么我们将 [ ] 与指向数组的指针一起使用?
- 如何将数组与指针一起使用?
- 在 for 循环中定义的临时数组,并分配给属于指针数组的指针
- 为什么数组到指针的输出不相关
- 尝试创建指向动态分配的字符数组的指针
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++中的指针数组排序算法
- 使用指向数组的指针进行插入排序
- 通过指针数组排序