Passing array of structure to function

Hello everyone. Trying to pass array of structures to a function named ageprint to print names of students of age 14. Error in lines 16 and 18. Please help
error: no match for 'operator[]' (operand types are 'Student' and 'int')
Thanks in advance
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
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int  j=4;
int i;
struct Student{
  string name;
  int age;
  int rollno;
}stud[4];
struct Student ageprint(Student stud)     //for age 14
    {
        cout<<"age 14 students"<<endl;
        for(i=0;i<j;i++)
        {
            if(stud[i].age == 14)
            {
                cout<<stud[i].name<<endl;
            }
        }
    }

int main()
{

    for(i=0;i<j;i++)
    {
        cout<<"enter name student"<<i+1<<endl;
        cin>>stud[i].name;
        stud[i].rollno = i+1;
        cout<<"enter age";
        cin>>stud[i].age;
    }
    ageprint(stud[i]);
return 0;
}
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
#include <iostream>
#include <string>

const int num_students = 4;

struct Student
{
   std::string name;
   int age;
   int rollno;
};

void ageprint(Student stud[])
{
   std::cout << "age 14 students\n";

   for (int i = 0; i < num_students; i++)
   {
      if (stud[i].age == 14)
      {
         std::cout << stud[i].name << '\n';
      }
   }
}

int main()
{
   Student stud[num_students];

   for (int i = 0; i < num_students; i++)
   {
      std::cout << "enter name student" << " #" << i + 1 << ": ";
      std::cin >> stud[i].name;
      stud[i].rollno = i + 1;
      std::cout << "enter age: ";
      std::cin >> stud[i].age;
   }
   std::cout << '\n';

   ageprint(stud);
}
enter name student #1: Dave
enter age: 14
enter name student #2: Sarah
enter age: 15
enter name student #3: Joe
enter age: 14
enter name student #4: Pete
enter age: 13

age 14 students
Dave
Joe
See "Arrays as parameters" in http://www.cplusplus.com/doc/tutorial/arrays/

Dependence on global variables and magic constants is restrictive. Consider:
1
2
3
4
5
6
7
8
9
10
11
12
void ageprint( Student stud[], int num, int age )
{
   std::cout << "age " << age << " students\n";

   for ( int i = 0; i < num; ++i )
   {
      if ( stud[i].age == age )
      {
         std::cout << stud[i].name << '\n';
      }
   }
}
Last edited on
Thanks everybody for providing solutions. I just saw your replies and my program has run correctly
Topic archived. No new replies allowed.