Open In App

How to create an Array of Objects in the Stack memory?

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

What is an Array of Objects?

An array of objects is a data structure that stores a collection of objects of the same type. The objects in the array are stored in contiguous memory locations, and the array provides indexed access to the objects. This means that you can access an individual object in the array using its index, just like you would with an array of primitive data types (e.g., int, float, etc.).

How to create an Array of Objects in the Stack memory?

To create an array of objects on the stack in C++, you can use the following syntax:

Type name[size];

Here, ‘Type‘ is the type of the objects in the array (e.g., int, float, MyClass, etc.); ‘name‘ is the name of the array, and size is the number of elements in the array.

For example:

int array[10];  // Creates an array of 10 integers
MyClass objects[20];  // Creates an array of 20 objects of type MyClass

Issues while creating an Array of Objects in Stack memory:

Keep in mind that creating an array of objects on the stack has some limitations. 

  • The size of the array must be a compile-time constant,  
  • The array is stored in the stack, which has limited space. If you need to store a large number of objects or if the size of the array is not known at compile time, you may want to consider using a dynamic array or creating the objects on the heap using new.

Algorithm:

Here is a simple algorithm that creates an array of n objects of type MyClass on the stack and initializes each object with a value val:

  • Define a variable array of type MyClass.
  • Iterate through the elements of the array. 
  • For each element i, do the following:
    • Call the default constructor of MyClass to create a new object in array[i].
    • Set the value of array[i] to val.

Below is the implementation of the above approach.

C++




// C++ code to generate array of object in stack memory
 
#include <bits/stdc++.h>
using namespace std;
 
// User defined class
class MyClass {
public:
    // Default constructor
    MyClass() {}
 
    // Setter function
    void setValue(int val) { value = val; }
 
    // Getter function
    int getValue() const { return value; }
 
private:
    // Data member to store the value
    int value;
};
 
// Driver code
int main()
{
    // Number of objects
    const int n = 5;
 
    // Value to initialize the objects with
    const int val = 10;
 
    // Create an array of n objects on the stack
    MyClass array[n];
 
    // Initialize each object with the value val
    for (int i = 0; i < n; i++) {
        array[i].setValue(val);
    }
 
    // Print the value of each object
    for (int i = 0; i < n; i++) {
        cout << "Object " << i << ": "
             << array[i].getValue() << endl;
    }
 
    return 0;
}


Python3




# Python code to generate array of objects in stack memory
 
# User defined class
class MyClass:
    # Default constructor
    def __init__(self):
        self.value = None
         
    # Setter function
    def setValue(self, val):
        self.value = val
 
    # Getter function
    def getValue(self):
        return self.value
 
# Driver code
if __name__ == '__main__':
    # Number of objects
    n = 5
 
    # Value to initialize the objects with
    val = 10
 
    # Create an array of n objects
    array = [MyClass() for _ in range(n)]
 
    # Initialize each object with the value val
    for i in range(n):
        array[i].setValue(val)
 
    # Print the value of each object
    for i in range(n):
        print("Object", i, ":", array[i].getValue())
# this code is contributed by dev


Java




import java.util.Arrays;
 
class MyClass {
    private int value;
 
    // Default constructor
    public MyClass() {}
 
    // Setter function
    public void setValue(int val) { value = val; }
 
    // Getter function
    public int getValue() { return value; }
}
 
public class Main {
 
    public static void main(String[] args) {
        // Number of objects
        final int n = 5;
 
        // Value to initialize the objects with
        final int val = 10;
 
        // Create an array of n objects on the stack
        MyClass[] array = new MyClass[n];
 
        // Initialize each object with the value val
        for (int i = 0; i < n; i++) {
            array[i] = new MyClass();
            array[i].setValue(val);
        }
 
        // Print the value of each object
        for (int i = 0; i < n; i++) {
            System.out.println("Object " + i + ": " + array[i].getValue());
        }
    }
}


C#




using System;
 
// User defined class
class MyClass
{
    private int value;
 
    // Default constructor
    public MyClass()
    {
    }
 
    // Setter function
    public void SetValue(int val)
    {
        value = val;
    }
 
    // Getter function
    public int GetValue()
    {
        return value;
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        // Number of objects
        const int n = 5;
 
        // Value to initialize the objects with
        const int val = 10;
 
        // Create an array of n objects on the stack
        MyClass[] array = new MyClass[n];
 
        // Initialize each object with the value val
        for (int i = 0; i < n; i++)
        {
            array[i] = new MyClass();
            array[i].SetValue(val);
        }
 
        // Print the value of each object
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine("Object " + i + ": " + array[i].GetValue());
        }
 
        Console.ReadLine();
    }
}
 
// Explanation:
// This C# code generates an array of n objects of the MyClass type, and initializes each object with the value val.
// It then prints the value of each object in the array.
// To do this, we create a new instance of the MyClass type for each object in the array, and then set the value of the object using the SetValue method. We then print the value of each object using the GetValue method.
// The const keyword is used to declare the n and val variables, which are constants and cannot be modified once set.


Javascript




// Javascript code to generate array of object in stack memory
 
// User defined class
class MyClass {
  constructor() {
    // Data member to store the value
    this.value = 0;
  }
 
  // Setter function
  setValue(val) {
    this.value = val;
  }
 
  // Getter function
  getValue() {
    return this.value;
  }
}
 
// Number of objects
const n = 5;
 
// Value to initialize the objects with
const val = 10;
 
// Create an array of n objects on the stack
const array = new Array(n).fill(null).map(() => new MyClass());
 
// Initialize each object with the value val
for (let i = 0; i < n; i++) {
  array[i].setValue(val);
}
 
// Print the value of each object
for (let i = 0; i < n; i++) {
  console.log(`Object ${i}: ${array[i].getValue()}`);
}


Output

Object 0: 10
Object 1: 10
Object 2: 10
Object 3: 10
Object 4: 10

Output:

Output of the previous code

Output of the previous code

Auxiliary space: O(n)

time complexity: O(n) 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads