Search code examples
c++dynamic-memory-allocationnew-expression

How to store a variable or object on desired memory location?


Let's suppose I have an object of a class as shown below:

Myclass obj;

Now I want to store this object to my desired memory location. How can I do this? Is it possible or not?

I have created an array class which simply insert data of integer type in respective indexes but the size of array is not declared inside the class. I insert small amount of data like 50 to 60 integers , then I use loop to insert a large data inside this class, but this time my program crashes , I think it is because of reason that if some index is encountered in memory which has some value in it , program stops itself. Now I want to analyze the memory that my object of array class start from that particular address which contain maximum number of available empty useable memory spaces

I think it is not allowing more insertions because of some allocated memory location. Now I want to place my object on that memory address which contain maximum available empty useable space. Please guide me

#include<iostream>
using namespace std;

class newarray 
{
public:
    int n;
    int arr[]; //size not declared 
    int* ptr;

    newarray():n(0),ptr(NULL)
    {
    }

    void getadress(int indexno) //for getting address of an index
    {
        ptr=&arr[indexno];
        cout<<endl<<ptr;
    }

    void insert(int a) //inserting an element
    {
        arr[n]=a;
        n++;
    }

    void display()
    {
        for(int i=0;i<=n;i++)
        {
            cout<<endl<<arr[i];
        }
    }
};

int main()
{
    newarray a1;
    int x=1;

    for(int i=0;i<100;i++) //work good with 100 inssertions
    //but if exceed to 300 or more it crashes.
    {
        a1.insert(x);
        x++;
    }
    a1.display();
}

Solution

  • You wrote

     class newarray 
        {
        int arr[]; //size not declared
    

    This is not allowed. Unfortunately, your compiler did not warn you when compilinhg. You only discovered that this was a problem when your code crashed.

    You then wonder about "some allocated memory location" and picking one manually. That's not the problem. int arr[] without explicitly specifying bounds is allowed only in a few contexts, such as a function declaration. The function declaration doesn't need a size because the size in that case is determined by the caller.

    Since this is C++, just use std::vector<int> for your dynamic arrays.