Horje
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 C

To create a dynamic array inside a structure in C, define a structure that contains a pointer to the array type and a variable to store the size of the array. Then initialize the dynamic array with that size using malloc() to dynamically allocate memory for the array.

Syntax to Create a Dynamic Array Inside a Structure

// Define the structure
struct StructName {
dataType* arrayName;
int size;
};

// In function
StructName variableName;
variableName.arrayName = new dataType[size];
variableName.size = size;


Here,

  • StructName is the name of the structure.
  • dataType is the type of data that the array holds
  • arrayName is the name of the array.
  • variableName is the name of the structure variable.
  • size is the size of the array.

C++ Program to Create a Dynamic Array Inside a Structure

The below program demonstrates how we can create a dynamic array inside a structure in C++.

C
// C Program to illustrate how to create a dynamic array
// inside a structure
#include <stdio.h>
#include <stdlib.h>

// Define the structure
typedef struct myStruct {
    int* myArray;
    int size;
} MyStruct;

int main()
{
    // Define the size of the array
    int size = 5;

    // Create a structure variable
    MyStruct s;

    // Create a dynamic array inside the structure
    s.myArray = (int*)malloc(sizeof(int) * size);
    s.size = size;

    // Initialize the array
    for (int i = 0; i < size; i++) {
        s.myArray[i] = i;
    }

    // Print the array elements
    for (int i = 0; i < size; i++) {
        printf("%d ", s.myArray[i]);
    }

    // Delete the dynamic array
    free(s.myArray);

    return 0;
}

Output
0 1 2 3 4 

Time Complexity: O(N), here N is the size of the array.
Auxiliary Space: O(N)






Reffered: https://www.geeksforgeeks.org


C Language

Related
How to Pass Array of Structure to a Function in C? How to Pass Array of Structure to a Function in C?
How to Add an Element to an Array of Structs in C? How to Add an Element to an Array of Structs in C?
Difference Between Matlab and C Language Difference Between Matlab and C Language
C/C++ Programs C/C++ Programs
LMNs-C/C++ LMNs-C/C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16