c++heap-memorydata-access

C++ Accessing the Heap


This problem involved me not knowing enough of C++. I am trying to access a specific value that I had placed in the Heap, but I'm unsure of how to access it. In my problem, I had placed a value in a heap from a data member function in an object, and I am trying to access it in another data member function. Problem is I do not know how, and I had searched examples online, but none were what I needed as they were all in int main() and were not specifically what I needed.

In the first data member function, I declare the value I want to be sent to the Heap; Here's an example of what my first data member function.

void Grid::HeapValues()
{
    //Initializing Variable
    value = 2; //The type is already declared

    //Pointers point a type towards the Heap
    int* pValue = new int;

    //Initialize  an a value of in the Heap
    *pValue = value;
}

And in data member function This is what want:

void Grid::AccessHeap()
{
    //Extracting heap:
    int heap_value = *pValue; //*pValue does not exist in this function
    cout << heap_value; //Delays the value 2, which is found
                        //in the first data member function
}

I feel foolish for asking, but I am unable to find the answers and do not how. Does anyone know how to access a value from the heap in a simple way? And I would need it to be able to access in more then two data member function.


Solution

  • pValue needs to be a member-variable of the class Grid.

    class Grid
    {
      private: int* pValue;
      public: void HeapValues();
              void AccessHeap();
    };
    

    Now the member-variable pValue is accessible from any member-function of Grid.