Returning pointers to struct members

Hi,

I want to write a class that returns a pointer to any data in an array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class CData
{
   private:
      struct
      {
	  void* pVoid;
	  int   iLen;
      }data;
 
   public:
      void  SetData (void* pVoid);
      void* GetData (int iNum);
};
 

void CData::SetData (void* pVoid)
{
   data.pVoid = pVoid;
   data.iLen  = iLen;
}
 

void* CData::GetData (int iNum)
{
   return data.pVoid + iNum*iLen;  //Simplified
}


With normal data arrays this isn't a problem, but for structures like this I need some help:
1
2
3
4
5
6
7
8
9
10
11
12
13
struct CHILD
{
   TCHAR szString [50];
   int   iInt;
};
 

struct MASTER
{
   CHILD* pChild;
   TCHAR  szString [50];
   int    iInt;
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
static MASTER master [3];
static CHILD  child;
 

_tcscpy (child.szString, TEXT ("Child main"));
child.iInt = 12;
 

master[0].pChild = master[2].pChild = &child;
master[1].pChild = new CHILD;
 

master[1].pChild->iInt = 11;
_tcscpy (master[1].pChild->szString, TEXT ("Child 1"));
_tcscpy (master[0].szString, TEXT ("Master 0"));
_tcscpy (master[1].szString, TEXT ("Master 1"));
_tcscpy (master[2].szString, TEXT ("Master 2"));
 

master[0].iInt = 20;
master[1].iInt = 21;
master[2].iInt = 22;

Returning data from the MASTER structure isn't a problem, but returning pointers to the data from the CHILD structs is a little bit more complicated because the structs are not placed into the memory with the same distance between them(?) So i guesse I have to work with pointers to pointers, but I have no idea how to start, so any ideas?
if I am doing c or c++ I need to allocate pointers in memory to use them, otherwise the well generate exception faults, because the pointer doesn't point anywhere specific.

for example if I set up like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

struct CHILD
{
   TCHAR szString [50];
   int   iInt;
};
 

struct MASTER
{
   CHILD* pChild;
   TCHAR  szString [50];
   int    iInt;
};

// in my code uses I will need
// this is for c.
MASTER myMaster;
myMaster.CHILD = malloc(sizeof(CHILD));

// this is for c++
master myMaster;
myMaster.CHILD = new(CHILD);

// now I can use the stuff...
myMaster.Child->szString = TCHAR("Hello");

// then I need to clean up..
// again in c++
delete myMaster.CHILD;

// again in c
free(myMaster.CHILD);


I hope this points you in a direction.
Last edited on
Topic archived. No new replies allowed.