A bit of an pointer to array of pointers problem

Discussion in 'C++' started by A, Dec 11, 2011.

  1. A

    A Guest

    Here is a situation:

    TCustomObject *pObjA[] = { Obj1, Obj2, Obj3 };
    TCustomObject *pObjB[] = { Obj4, Obj5, Obj6 };
    TCustomObject *pObjC[] = { Obj7, Obj8, Obj9 };

    for (int i = 0; i < ( sizeof(pObjA) / sizeof(pObjA[0]) ); i++)
    {
    // do something with pObjA...
    }

    How would you add a pointer to array of pointers so that if a code needs
    array A array (Obj1, Obj2 and Obj3)
    but if it needs B or C it needs Obj4-6 or Obj7-9?

    If I put a pointer to a pointer like this:

    TCustomObject **pObjUsed = pObjA;

    Then to get Obj1 I would need to do something like:

    pObjUsed-> (here use Obj1)

    How would you rewrite this for for loop to be able to use any of 3 arrays?
     
    A, Dec 11, 2011
    #1
    1. Advertisements

  2. A

    A Guest

    To clarify this a bit, I need a pointer to array not a pointer to a pointer
    I guess...
     
    A, Dec 11, 2011
    #2
    1. Advertisements

  3. A

    A Guest

    TCustomObject *pObjA[] = { Obj1, Obj2, Obj3 };
    Another attempt to explain what I want :)

    I need a variable that points to element 1 of pObjA to access Obj1, then,
    when I increase this variable to point to element 2 (Obj2).
    But if pObjB is needed then the same variable needs to point at element 1 of
    pObjB (Obj4) and when increased to point to element 2 (Obj5) etc.
     
    A, Dec 11, 2011
    #3
  4. A

    Pavel Guest


    TCustomObject *pObjUsed = needA() ? &pObjA[0]
    : needB() ? &pObjB[0]
    : /* assume or assert needC() */ &pObjC[0];


    for (int i = 0; i < ( sizeof(pObjA) / sizeof(pObjA[0]) ); i++)
    {
    // to do something with pObj{A|B|C}, refer to pObjUsed

    }

    Is this what you wanted?

    HTH,
    -Pavel
     
    Pavel, Dec 12, 2011
    #4
  5. A

    A Guest

    that would be that except that my compiler reports that it cannot convert
    object type:
    it is C++ Builder - Cannot convert 'TNotifyEvent' to 'TNotifyEvent' (if I
    use TNofifyEvent instead of TCustomObject).

    I think this is compiler specific so I'll look for more help elsewhere.
    Thanks for the answer though.
     
    A, Dec 12, 2011
    #5
  6. A

    Pavel Guest

    Yeah, I was wrong, it should have been


    TCustomObject **pObjUsed = needA() ? &pObjA[0]
    : needB() ? &pObjB[0]
    : /* assume or assert needC() */ &pObjC[0];


    and then refer to pObjUsed for a pointer or *pObjUsed for an object
     
    Pavel, Dec 12, 2011
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.