【发布时间】:2015-07-04 04:13:04
【问题描述】:
您好,我是编程新手,正在努力使用这些应用程序。这是错误代码:
错误 C3078 你不能“新建”一个未知边界数组第 17 行
我很难理解和掌握指针的概念。任何帮助都非常感谢您查看我的代码。
#include <iostream>
#include <iomanip>;
using namespace std;
//function prototypes
int getArray(int num);
void selectionsortArray(int *[], int);
double findAverage(int *scores, int nums);
void showSortedArray(int *[], int);
int main()
{
int *scores = new int[]; // To dynamically allocate an array
double total = 0, //accumulator
average; //to hold average test scores
int testScores, // To hold the amount of test scores the user will enter
count; //Counter variable
// Request the amount of test scores the user would like to enter
cout << "How many test scores do you wish to process: ";
cin >> testScores;
getArray(testScores);
selectionsortArray(&scores, testScores);
cout << "Test scores sorted:\n\n";
showSortedArray(&scores, testScores);
average = findAverage(scores, testScores);
//set precision
cout << setprecision(2) << fixed;
cout << "\tAverage Score\n";
cout << average;
}
int getArray(int num)
{
int *array, ptr; //set array pointer equal to 0
int count;
cout << "\tPlease enter Test Scores by percent:\n";
for (count = 0; count < num; count++)
{
cout << "Test score #" << (count+1)<< ": ";
cin >> array[count];
}
ptr = *array; //Set the ptr to be returned with the array
return ptr; // return ptr
}
void selectionsortArray(int *arr[], int testScores)
{
int startscan, minIndex;
int *minElem;
for (startscan = 0; startscan < (testScores - 1); startscan++)
{
minIndex = startscan;
minElem = arr[startscan];
for(int index = startscan + 1; index < testScores; index++)
{
if (*(arr[index]) < *minElem)
{
minElem = arr[index];
minIndex = index;
}
}
arr[minIndex] = arr[startscan];
arr[startscan] = minElem;
}
}
void showSortedArray(int *arr[], int testScores)
{
for ( int count = 0; count < testScores; count ++)
cout << *(arr[count]) << " \n";
}
double findAverage(int *scores, int testScores)
{
double average = 0;
for (int count = 0; count < testScores; count++)
average += scores[count];
average /= testScores;
return average;
}
【问题讨论】:
-
这段代码有多个严重的问题。
getArray写入一个野指针,并返回一个 int。getArray中的 cmets 是错误的(他们说了什么,但代码实际上做了其他事情)。selectionsortArray错误地使用arr,这甚至无法编译。您似乎缺少对指针是什么的基本理解——返回并查看您的笔记或其他关于指针如何工作的内容。 -
感谢您的帮助。由于某种原因,我一直在为指针而苦苦挣扎,并且不太明白在什么情况下,为什么以及用什么来取消引用和引用。0 我一直在回头看,但似乎并没有坚持下去。使用 get array 中的评论只是不好的做法。我让代码做一件事并决定更改它并且从未更改过 cmets .....也许找到视频或在线阅读会有所帮助。再次感谢您的宝贵时间!
标签: c++