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,
StructNameis the name of the structure.dataTypeis the type of data that the array holdsarrayNameis the name of the array.variableNameis the name of the structure variable.sizeis 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 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)