Program to Store Data in Structures Dynamically - (C Programs)
In C programming, structures are used to store data of different types. This program demonstrates how to store data in structures dynamically. By allocating memory dynamically, we can store the data and add or remove elements from the structure as needed.
Syntax
#include <stdio.h>
#include <stdlib.h>
struct student {
int id;
char *name;
float gpa;
};
int main() {
struct student *s;
s = (struct student *) malloc(sizeof(struct student));
s->id = 1;
s->name = "John Doe";
s->gpa = 3.5;
free(s);
}
Example
In this example, we create a structure student
with id
, name
, and gpa
fields. We then allocate memory dynamically for the structure using the malloc()
function. We assign values to the structure fields and free the allocated memory using the free()
function.
#include <stdio.h>
#include <stdlib.h>
struct student {
int id;
char *name;
float gpa;
};
int main() {
struct student *s;
s = (struct student *) malloc(sizeof(struct student));
s->id = 1;
s->name = "John Doe";
s->gpa = 3.5;
printf("Student ID: %d\n", s->id);
printf("Name: %s\n", s->name);
printf("GPA: %.2f\n", s->gpa);
free(s);
}
Output
Student ID: 1
Name: John Doe
GPA: 3.50
Explanation
In this program, we create a structure student
with three fields: id
of type int
, name
of type char *
, and gpa
of type float
. We then allocate memory dynamically for this structure using the malloc()
function.
We assign values to the id
, name
, and gpa
fields of the structure using the ->
operator. Finally, we print the values of these fields using printf()
statements.
After printing the values, we free the memory allocated to the structure using the free()
function.
Use
This program can be used to store data of different types in structures dynamically. By allocating memory dynamically, we can add or remove elements from the structure as needed.
Summary
In this tutorial, we discussed how to store data in structures dynamically using C programming. We covered the syntax, example, output, explanation, use, and important points of dynamically allocating memory for structures. By using dynamic memory allocation, we have the flexibility to store data of different types in structures and make changes to the structure as needed.