Skip to content

Commit 46d8efd

Browse files
authored
Create Dynamic Memory Allocation for Structure
1 parent 633aa8a commit 46d8efd

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//C Program to Store Information Using Structures with Dynamically Memory Allocation
2+
3+
#include <stdio.h>
4+
#include<stdlib.h>
5+
struct course
6+
{
7+
int marks;
8+
char subject[30];
9+
};
10+
int main()
11+
{
12+
struct course *ptr;
13+
int i, noOfRecords;
14+
printf("Enter number of records: ");
15+
scanf("%d", &noOfRecords);
16+
// Allocates the memory for noOfRecords structures with pointer ptr pointing to the base address.
17+
ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));
18+
for(i = 0; i < noOfRecords; ++i)
19+
{
20+
printf("Enter name of the subject and marks respectively:\n");
21+
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
22+
}
23+
printf("Displaying Information:\n");
24+
for(i = 0; i < noOfRecords ; ++i)
25+
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
26+
return 0;
27+
}
28+
29+
/*output
30+
31+
Enter number of records: 2
32+
Enter name of the subject and marks respectively:
33+
Programming
34+
22
35+
Enter name of the subject and marks respectively:
36+
Structure
37+
33
38+
39+
Displaying Information:
40+
Programming 22
41+
Structure 33
42+
*/
43+
44+

0 commit comments

Comments
 (0)