Pointers to structure

Hi friends here is my code please have a look at end i'll tell you what is wrong
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
#include <iostream>
#include <conio.h>
using namespace std;
struct employee{
	int empID;
	char empName[20];
	int empGrade;
};
int main()
{
	employee user[3];
	employee* users;
	for(int i = 0;i<3;i++)
	{
		cout<<"Employee NO."<<i+1<<endl;
		cout<<endl;
		cout<<"Please enter the id of the employee NO.:  ";
		cin>>user[i].empID;
		cout<<"Please enter the Name of the employee NO.:  ";
		cin>>user[i].empName;
		cout<<"Please enter the grade of the employee NO.:  ";
		cin>>user[i].empGrade;
		cout<<endl;
		cout<<endl;
		
	}
	cout<<"               "<<"ID"<<'\t'<<"Name"<<'\t'<<"Grade"<<'\t'<<endl;
	cout<<endl;
	for(int i = 0;i<2;i++)
	{
			cout<<"Employee NO."<<i+1<<": ";
			    cout<<user[i].empID<<'\t'<<user[i].empName<<'\t'<<user[i].empGrade<<endl;
			cout<<endl;
	}
	_getch();
}


You noticed that i have created a pointer for nothing but my teacher ask me to use that pointer to assign the values to each data member of the array
how can i do that i don't under stand i mean how can i use one pointer to point to different locations or my thinking is wrong is it possible
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	employee user[3];
	employee* users = user;
	for(int i = 0;i<3;i++)
	{
		cout<<"Employee NO."<<i+1<<endl;
		cout<<endl;
		cout<<"Please enter the id of the employee NO.:  ";
		cin>>users->empID;
		cout<<"Please enter the Name of the employee NO.:  ";
		cin>>users->empName;
		cout<<"Please enter the grade of the employee NO.:  ";
		cin>>users->empGrade;
		cout<<endl;
		cout<<endl;

                ++users ;  // point to the next user
	}
Last edited on
It can also be done without using pointer arithmetic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
employee user[3]
employee* users;
for(int i = 0;i<3;i++)
{
    users = &user[i];
    cout<<"Employee NO."<<i+1<<endl;
    cout<<endl;
    cout<<"Please enter the id of the employee NO.:  ";
    cin>>users->empID;
    cout<<"Please enter the Name of the employee NO.:  ";
    cin>>users->empName;
    cout<<"Please enter the grade of the employee NO.:  ";
    cin>>users->empGrade;
    cout<<endl;
    cout<<endl;
}
Topic archived. No new replies allowed.