Question

I have added the CString value in CPtrList. And using Find function. When I try to Find the CString value using Find method of CPtrList, I always got NULL position.

Below is my code to add the CString value in CPtrList ptrFolderPath:

CString sTemp;// 

ptrFolderPath.AddTail(new CString (sTemp));

While searching I using below code:

POSITION pos = ptrFolderPath.Find(sPath.GetBuffer(sPath.GetLength()));

here sPath is a CString.

But the pos value is always NULL.

Any idea, where I am missing?

Was it helpful?

Solution

The key point is a line in the MSDN Help for CPtrList::Find(): "Note that the pointer values are compared, not the contents of the objects."

When your code calls "new CString (sTemp)" a new CString object is created, and what is returned (and added to the CPtrList) is the pointer value - the location in memory of your new CString. Let's say, for example, this is at memory location 0x001234500.

Your code that calls Find() is passing in the address of character buffer, but, even if this contains the same string characters as your above CString, its location in memory will be completely different. Since you're not passing in 0x0012234500 (in this example), you don't find the entry you expect.

Given what you appear to be trying to do, CPtrList is probably not the appropriate container type - something like CStringList would be more suitable, since there comparisons are done by value (i.e. the contents of the string) not by pointer.

If all this doesn't make sense, I'm afraid that you need to spend some time reading up on pointers, and concepts such as the difference between equality (two different objects that have the same value) and identity (different references to the same object)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top