-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct-arrays.c
71 lines (52 loc) · 1.38 KB
/
struct-arrays.c
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
61
62
63
64
65
66
67
68
69
70
71
/**
* @file struct-arrays.c
* @author your name ([email protected])
* @brief
* @version 0.1
* @date 2022-04-07
*
* @copyright Copyright (c) 2022
*
*/
// Structure array
// Create a structure array for a class of students,
// and then print the structure using function.
// 2 functions - simple print, print using pointers
#include<stdio.h>
#include<stdlib.h>
struct student {
char* name;
int age;
};
void printClassInfo(struct student class[], int no_of_students) {
int i;
for (i = 0; i < no_of_students; i++) {
printf("Name of the student is -> %s\n", class[i].name);
printf("Age of the student is -> %d\n", class[i].age);
}
}
void printClassInfoUsingPointer(struct student* p, int no_of_students) {
int i;
for (i = 0; i < no_of_students; i++) {
printf("Name of the student is -> %s\n", (*(p + i)).name);
printf("Age of the student is -> %d\n", (*(p + i)).age);
}
}
int main (void) {
struct student class[10];
struct student std;
std.name = "john";
std.age = 21;
class[0] = std;
std.name = "jane";
std.age = 20;
class[1] = std;
printClassInfo(class, 2);
struct student* p = malloc(2 * sizeof(struct student));
(*(p)).name = "john";
(*(p)).age = 21;
(*(p + 1)).name = "jane";
(*(p + 1)).age = 20;
printClassInfoUsingPointer(&(p[0]), 2);
return 0;
}