VOOZH about

URL: https://www.geeksforgeeks.org/dsa/how-to-create-an-array-of-objects-in-the-stack-memory/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 6 Apr, 2023

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.


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) 

Comment