Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
How to Dynamically Create Array of Structs in C?
Next article icon

How to Create a Dynamic Array of Structs?

Last Updated : 01 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, we have dynamic arrays in which we can allocate an array of elements whose size is determined during runtime. In this article, we will learn how to create a dynamic array of structures in C.

Create a Dynamic Array of Structs in C

A dynamic array of structs in C combines dynamic arrays and structures to organize and store multiple pieces of related information, each being implemented as a structure.

We can create a dynamic array of structs using the malloc() funciton. This function takes the required size of the memory as an argument and returns the void pointer to the allocated memory. We can then convert this pointer to struct type using typecasting.

Note: When the usage of dynamic array is done, free the allocated memory to avoid memory leaks.

C Program to Create a Dynamic Array of Structs

The below example demonstrates how we can initialize and access members of a dynamic array of structures in C.

C
// C program to declare and use dynamic array of structure  #include <stdio.h> #include <stdlib.h>  // Define a structure to represent a student struct Student {     char name[50];     int age; };  int main() {      // Declaring a pointer to a structure and allocating     // memory for initial (3) students     struct Student* students         = (struct Student*)malloc(3 * sizeof(*students));      // Check for malloc Failure     if (students == NULL) {         fprintf(stderr, "Memory allocation failed\n");         return 1;     }      // Providing some sample data for the students     for (int i = 0; i < 3; i++) {         snprintf(students[i].name, sizeof(students[i].name),                  "Student%d", i + 1);         students[i].age = 20 + i;     }      // Displaying the student data     printf("Student Data:\n");     for (int i = 0; i < 3; i++) {         printf("Student %d: Name - %s, Age - %d\n", i + 1,                students[i].name, students[i].age);     }      // free the memory when done     free(students);     return 0; } 

Output
Student Data:  Student 1: Name - Student1, Age - 20  Student 2: Name - Student2, Age - 21  Student 3: Name - Student3, Age - 22  



Explanation: In the above example we defined the Student structure and dynamically allocates memory for an array of three Student instances. It populates each student's data using a loop and snprintf for names and sequential ages. The student information is displayed using another loop. Finally, it frees the allocated memory to prevent memory leaks.


Next Article
How to Dynamically Create Array of Structs in C?

R

rveerendra400
Improve
Article Tags :
  • C Programs
  • C Language
  • c-array
  • C-Structure & Union
  • C-Dynamic Memory Allocation
  • C Examples

Similar Reads

  • How to Dynamically Create Array of Structs in C?
    In C, an array is a data structure that stores the collection of elements of similar types. Structs in C allow the users to create user-defined data types that can contain different types of data items. In this article, we will learn how we can create an array of structs dynamically in C. Dynamicall
    2 min read
  • How to Create a Dynamic Array of Strings in C?
    In C, dynamic arrays are essential for handling data structures whose size changes dynamically during the program's runtime. Strings are arrays of characters terminated by the null character '\0'. A dynamic array of strings will ensure to change it's size dynamically during the runtime of the progra
    3 min read
  • How to Create a Dynamic Array Inside a Structure?
    In C, the structure can store the array data types as one of its members. In this article, we will learn how to create a dynamic array inside a structure in C. Creating a Dynamic Array Inside a Structure in CTo create a dynamic array inside a structure in C, define a structure that contains a pointe
    2 min read
  • How to Create an Array of Structs in C?
    In C, a structure is a user-defined data type that can be used to group items of different types into a single entity while an array is a collection of similar data elements. In this article, we will learn how to create an array of structs in C. Creating an Array of Structs in CTo create an array of
    2 min read
  • How to Create a Dynamic Library in C?
    In C, a dynamic library is a library that is loaded at runtime rather than compile time. We can create our own dynamic libraries and use them in our programs. In this article, we will learn how to create a dynamic library in C. Example: Input:Hello, geeksforgeek!Output:Hello, geeksforgeek!Creating a
    2 min read
  • How to Delete an Element from an Array of Structs in C?
    In C, an array of structs refers to the array that stores the structure variables as its elements. In this article, we will learn how to delete an element from an array of structures in C. For Example, Input: struct Person persons[3] = { { "Person1", 25 }, { "Person2", 30 }, { "Person3", 22 }, }; Ta
    2 min read
  • How to Initialize a Dynamic Array in C?
    In C, dynamic memory allocation is done to allocate memory during runtime. This is particularly useful when the size of an array is not known at compile time and needs to be specified during runtime. In this article, we will learn how to initialize a dynamic array in C. Initializing a Dynamic Arrays
    2 min read
  • How to Find Size of Dynamic Array in C?
    In C, dynamic memory allocation allows us to manage memory resources during the execution of a program. It’s particularly useful when dealing with arrays where the size isn’t known at compile time. In this article, we will learn how to find the size of a dynamically allocated array in C. Find Size o
    2 min read
  • How to Access Array of Structure in C?
    In C, we can create an array whose elements are of struct type. In this article, we will learn how to access an array of structures in C. For Example, Input:myArrayOfStructs = {{'a', 10}, {'b', 20}, {'A', 9}}Output:Integer Member at index 1: 20Accessing Array of Structure Members in CWe can access t
    2 min read
  • How to Add an Element to an Array of Structs in C?
    In C, a struct is a user-defined data type that allows the users to group related data in a single object. An array of structs allows to store multiple structs in contiguous memory locations. In this article, we will learn how to add an element to an array of structs in C. Example: Input: structArra
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences