COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
employee.c
Go to the documentation of this file.
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5struct Employee {
6 char Name[100];
7 char Position[100];
8 int Salary;
9};
10
11typedef struct Employee Employee;
12
13void setEmployee(char n[], char p[], int sal, Employee *e){
14 // strcpy parameters are (destination, source)
15 strcpy(e->Name, n);
16 strcpy(e->Position, p);
17 e->Salary = sal;
18}
19
21 printf("Name: %s\n", e.Name);
22 printf("Position: %s\n", e.Position);
23 printf("Salary: %d\n", e.Salary);
24}
25
26int main() {
27 int numOfEmployee;
28 scanf("%d", &numOfEmployee);
29 Employee *e;
30 e = (Employee *)malloc(numOfEmployee * sizeof(Employee));
31 for (int i = 0; i < numOfEmployee; i++) {
32 char n[100], p[100];
33 int sal;
34 scanf("%s%s%d",n,p,&sal);
35 setEmployee(n,p,sal,&e[i]);
36 // Instead of &e[i], e+i also works since it is an array.
37 // What is e+i? It is the address of the i-th element of the array.
38 // But why we can directly add i to it? isnt the array address is affected by the size of the struct?
39 // Yes, it is. But the compiler knows the size of the struct and it will automatically add the correct amount of bytes to the address.
40 // So, e+i is the same as &e[i].
41 }
42 for (int i = 0; i < numOfEmployee; i++) {
43 showInfo(e[i]);
44 }
45 free(e);
46 return 0;
47}
void showInfo(Employee e)
Definition employee.c:20
int main()
Definition employee.c:26
void setEmployee(char n[], char p[], int sal, Employee *e)
Definition employee.c:13
char Position[100]
Definition employee.c:7
char Name[100]
Definition employee.c:6
int Salary
Definition employee.c:8