views:

105

answers:

3

I'm having a pointer problem that I can't seem to figure out. It seems like I've used pointers in this way a 1000 times so I'm not quite sure what is going on here. I have the following code:

int iRetVal;
CycleCountOrder* cycleOrder =  NULL;
CycleCountLineItem* cycleLine = NULL;


iRetVal = m_CycleCount.GetCCOrderLine(pOneLocation.szOrderNum[c], cycleOrder, cycleLine);

Whenever I call GetCCOrderLine I step inside the function and it assigns valid values to the pointers cycleOrder and cycleLine. When I step outside of the function GetCCOrderLine the references are NULL again. The code below is how the GetCCOrderLine is defined:

header file

int GetCCOrderLine(CString szOrderLnitem, CycleCountOrder* cycleOrder, CycleCountLineItem* cycleCountLine);

cpp file

int CCycleCount::GetCCOrderLine(CString szOrderLnitem, CycleCountOrder* cycleOrder, CycleCountLineItem* cycleCountLine)
{
    CString szCurrOrderLnitem;
    for(int c = 0; c < m_Orders.GetCount(); c++)
    {
        CycleCountOrder* currentOrder = m_Orders[c];

        for(int d = 0; d < currentOrder->m_LineItems.GetCount(); d++)
        {
            CycleCountLineItem* currentLine = currentOrder->m_LineItems[d];

            szCurrOrderLnitem.Format("%s-%d-%d", currentOrder->szOrderNum, currentLine->nLnitemNum, currentLine->nSubitemNum);

            if(szCurrOrderLnitem == szOrderLnitem)
            {
                cycleOrder = currentOrder;
                cycleCountLine = currentLine;
                return FUNC_OK;
            }
        }
    }

    return FUNC_ERROR;
}

Also the two arrays that are being accessed in the above code and that are being used to assign values to the pointers passed in are declared as follows. Also these arrays are filled with objects created with the new operator:

CArray<CycleCountOrder*, CycleCountOrder*> m_Orders;
CArray<CycleCountLineItem*, CycleCountLineItem*> m_LineItems;
+3  A: 

Pass by Reference

Vinay
+5  A: 

Your function should receive pointer to pointer if you want to modify the original pointer.

Otherwise you just get the copy of the pointer values and you modify this copy.

// will modify the copy
void ptr( MyClass * ptr_copy )
{
    ptr_copy = new MyClass();
}

// will modify the original ptr
void ptr2ptr( MyClass ** ptr_2_ptr )
{
    *ptr_2_ptr = new MyClass();
}
Dmitry Yudakov
sbi
+4  A: 

Pass the pointers by reference if you wish the changes to the pointers to be reflected in the caller.

#include <iostream>
using namespace std;

void f(int *pnochange, int *&pchange){
   pnochange++;
   pchange++;
}

int main(){
   int buf[] = {1, 2};

   int *p1, *p2;
   p1 = p2 = buf;

   f(p1, p2);

   cout << *p1 << *p2;    // prints 12
}
Chubsdad