I have defined my own object type myClass, and in another class I am storing a list of instances of these objects. I have written the method below to return a subset of the list, based on some property of the object. However, if I modify one of the objects in the returned sublist, it is not reflected by the same object in the main list. Any advice on what I am doing wrong and how to resolve this problem would be greatly appreciated:
myClass* myList::getTaggedNames(size_t *listSize)
{
size_t taggedCapacity = 10;
size_t taggedCount = 0;
myClass* taggedList = new myClass[taggedCapacity];
for(size_t i = 0; i < numNames; i++) // numNames is global var count of names in main list
{
if(names[i].isTagged()) // names is the global list
{
if(taggedCount >= taggedCapacity)
{ // expand local list if necessary
myClass* largerList;
largerList = new myClass[taggedCapacity+5];
copy(taggedList, taggedList+taggedCount, largerList);
delete [] taggedList;
taggedList = largerList;
taggedCapacity += 5;
}
taggedList[taggedCount] = names[i];
taggedCount ++;
}
}
*listSize = taggedCount;
return taggedList;
}
Since 'taggedList' and 'names' are addressing different memory blocks you can copy (like you do with taggedList[taggedCount] = names[i];) but the're still independent and changes to one does not effect the other
I tried using an array of pointers here to try and get the 'taggedList' to contain pointers to the objects in 'names', but I was getting a segmentation fault when I tried to run it:
well i'd suggest that you use std::vector which does all the dynamic growing magic for you.
this is wrong:
1 2
myClass** taggedList;
*taggedList = new myClass[taggedCapacity];
it has to be
1 2 3 4 5
myClass** taggedList = new myClass*[taggedCapacity]; // creating an array of pointer
for(int i = 0; i < taggedCapacity; ++i) // fill the array of pointer
{
taggedList[i] = new myClass;
}
Oooh, thank you! That seems to work now. I did try to switch over to using a vector at one point, but then my code got completely messed up so I reverted back to this. I will look into using vectors for the future.
Thanks!