0

I Have a similar issue like the one listed here pointer-to-a-pointer-to-a-struct-giving-headache
my issue is different because i don't want multi instances from LISTOFONES i want Multi instances of ONE's Pointers like

class ONE {  
    int id;  
    char *name;  
};

class LISTOFONES {
    ONE **pointers;
    char *name;

    LISTOFONES ();
    ~LISTOFONES ();
};  

What to do to have a correct and memory safe initialization of the pointers variable with
1- pure c++ .. not stl containers
2- 100% dynamic not [] array limitation
3- Completely Memory Safe ( All Pointers safely point to a valid class too )

EDIT:
This is Not Home Work
and For what i want i only want to know what is the method to correctly init the pointers in the 'pointers' variable

EDIT
I Am trying to Achieve a Pointer List (array) Pointed by the Pointer pointers
Each Pointer points to the ONE struct

5
  • 9
    "STL containers" qualify as pure C++, since they're defined in the C++ language standard. There's no good reason to avoid them unless this is homework, in which case you should say so and tag your question as such. Commented May 19, 2011 at 22:03
  • stl containers are pure c++ :) Commented May 19, 2011 at 22:04
  • It's not clear why you want LISTOFONES::pointers to be a ONE** rather than a ONE*. What are you trying to achieve here? Commented May 19, 2011 at 22:15
  • You are posting decelerations without code, and no explanation of the problem you are having. Please elaborate. Commented May 19, 2011 at 22:31
  • @ildjarn - I suppose he wants to be able to grow his array. Copying pointers will be cheaper than copying objects. Commented May 19, 2011 at 22:34

1 Answer 1

2

If it were me, I would allocate an array of ONE*s thus:

pointers = new ONE*[reserve];

I would arrange that the first several members of the pointers array pointed to valid ONE objects. The last remaining members would all be zero (not essential, since they will never be derferenced.)

When I needed to grow the array, I would call new with a bigger size:

newPointers = new ONE*[newReserve];

and I would copy all of the pointers from previous array to the new array.

void
LISTOFONES::push_back(const ONE& one) {
  if(_size>=_reserve) {
    std::size_t newReserve = _reserve?(_reserve*2):1;
    ONE** newPointers = new ONE*[newReserve];
    std::copy(this->pointers, this->pointers+_size, newPointers);
    std::fill(newPointers+_size, newPointers+newReserve, (ONE*)0);
    std::swap(this->pointers, newPointers);
    _reserve = newReserve;
    delete[] newPointers;
  }
  this->pointers[_size] = new ONE(one);
  ++_size;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.