What's wrong with my program??

/*Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores.
Once all the scores are entered, the array should be passed to a function that sorts them in ascending order.
Another function should be called that calculates the average score.
The program should display the sorted list of scores and averages with appropriate headings.
Use pointer notation rather than array notation whenever possible and make sure you delete the array after displaying the scores.
Input Validation: Do not accept negative numbers for test scores.*/


#include <iostream>
#include <string>

using namespace std;

int main()
{
short amount;

cout<<"Enter the total number of students: ";
cin>>amount;

short *score=new short[amount];
string *name=new string[amount];

for (int i=0; i<amount; i++)
{
cout<<"Enter the name of student # "<<i+1<<endl;
cin>>*name;
cout<<"Enter the score of student # "<<i+1<<endl;
cin>>*score;

if (i+1!=amount)
{
*name++;
*score++;
}
}
short tempS;
string tempN;

for (int j=amount; j>=1; j--)
{
for (int i=0; i<j; i++)
{
if (score[i]>score[i+1])
{
tempS=score[i+1];
score[i+1]=score[i];
score[i]=tempS;
tempN=name[i+1];
name[i+1]=name[i];
name[i]=tempN;

}
}
}

double avg=0;
for(int i=0; i<amount; i++)
{
cout<<name[i]<<"\t"<<score[i]<<endl;
avg+=score[i];
}
avg=avg/amount;

cout<<endl<<"Average score is "<<avg;

system("pause");
}
I'll start it off and get you passed the reading of the input data. I see what you are dong here cin>>*name; but that is not the right way to do it. It's an array so use the index to help you cin>>name[i];. Now you can get rid of the pointer increment *name++;. Do this for both name and score. What is causing the segfault is you have incremented the pointer values of names and score and when you try to now sort them, you have gone beyond the memory allocated to them.
Also, when you get to the sorting you are trying to index i+1 in one case which equal 3. That also is going to cause a segfault. Print out the values of the index before you use them to see where it is going wrong.
Last edited on
Topic archived. No new replies allowed.