Pointers

I'm having trouble figuring out how to implement pointers that give the names of those who scored points along with the points that they scored. This is what I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;

#define MAX 23

int main()
{
    int arr[MAX];
    
    int n,i,j;
    int temp;
    float sum=0.0, average;
    
    cout<<"Enter the total number of scores:";
    cin>>n;

    if(n<0 || n>MAX)
    {
        cout<<"There aren't more then 23 players on a rugby team!"<<endl;
        return -1;
    }
    
    for(i=0;i<n;i++)
    {
        cout<<"Enter score: ["<<i+1<<"] ";
        cin>>arr[i];
    }
    
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(arr[i]>arr[j])
            {
                temp  =arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
    
    
    cout<<"Sorted scores in ascending order:"<<endl;
    for(i=0;i<n;i++)
        cout<<arr[i]<<"\t";
    cout<<endl;
    
    for(i = 0; i < n; ++i)
    {
        sum += arr[i];
    }

    average = sum / n;
    cout << "Average = " << average;
    
    
   
    return 0;
    
}
1
2
3
4
5
 if(n<0 || n>MAX)
    {
        cout<<"There aren't more then 23 players on a rugby team!"<<endl;
        return -1;
    }

first, you have a magic 23 in your text; it should be cout << "words" << MAX << "morewords" but that is irrelevant. Also, this logic will say that you have more than max if you put in -3 for input. That seems odd. Also, its than, not then.


all that aside, I believe you want a struct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct namescore
{
   int score;
   string name;
};

namescore arr[max];

  for(i=0;i<n;i++)
    {
        cout<<"Enter score: ["<<i+1<<"] ";
        cin>>arr[i].score;
        cout<<"Enter name: ["<<i+1<<"] ";
        cin>>arr[i].name;
    }
    

and so on. everywhere you had arr before, you now need arr[index].field so your sort and so on all need to do it that way. be SURE that your swap in the sort moves BOTH fields, not just the score... ideally you would add an assignment operator (and, I always mess this up, but it may actually generate one for you for this simple struct, sometimes it can do that) so that you don't have to touch each field to copy (like in your swap statements).

I have no idea what you wanted a pointer for. I can use one, if you want one just to have it, but you don't need one. You could make arr dynamic:
namescore * arr;
arr = new namescore[n]; //can be a variable now, unlike array needed max
...
and when done
delete[] arr;
Last edited on
Thanks for the guidance. The only reason I wanted to use a pointer was because we recently learned about ptrs in class but other than that thanks.
Topic archived. No new replies allowed.