Use type declared later in a structure

1

I have these structures

typedef struct stDC {
    qint8 numberA;
    qint16 numberB;
    qint32 numberC;
    qint64 numberD;
    qint32 *intList;
    qint8 *byteList;
    stDC *list;
    int listlen;
    QString string;
    int mode;
    float floatv;
    double doublev;
} DataComplex;

typedef struct stTab {
    QString name;
    DataComplex value;
} Tab;

typedef struct stTree {
    QString name;
    Tab data[255];
    int data_n;
    stTree *branches[255];
    int branches_num;
} Tree;

But do I need to add an array of Tree pointers to DataComplex is this possible ?, and if it is as?

    
asked by sanandresm 23.12.2017 в 02:49
source

1 answer

1

It is perfectly possible; and, in addition, very simple: pre-declaring :

struct stTree; // <- PRE-DECLARAMOS.

typedef struct stDC {
  qint8 numberA;
  qint16 numberB;
  qint32 numberC;
  qint64 numberD;
  qint32 *intList;
  qint8 *byteList;
  stDC *list;
  int listlen;
  QString string;
  int mode;
  float floatv;
  double doublev;
  stTree *que_facil_es[1024]; // <-- AQUÍ.
} DataComplex;

In the pre-declaration, we inform the compiler that an identifier is a class; thus, when the compiler finds this identifier, it knows that we are going to declare it sooner or later, and it does not complain.

If you look closely, you'll see that you're already doing it , even before asking the question:

typedef struct stTree {
  QString name;
  Tab data[255];
  int data_n;
  stTree *branches[255]; // <-- ¿¿ Cómo es posible esto ??
};

How is it possible that you use a array of pointers to stTree before you finish declaring the struct ?

This technique is only valid if we are going to use pointers or references ; for example:

struct stTree; // <- PRE-DECLARAMOS.

typedef struct stDC {
  qint8 numberA;
  ...
  stTree que_facil_es; // <-- ESTO ES UN ERROR.
} DataComplex;

Think that the compiler needs to know the size of the types; in the previous code, does not know ; therefore, he does not know how much memory he has to use, and he complains .

However, always knows the size of a pointer , which is what you really want to use; therefore, with saying that stTree is a valid type, you do not need more.

One last thing: in C ++, it is not necessary to do typedef for classes (nor for struct , which is a type of class):

struct Tree;

struct DataComplex {
  qint8 numberA;
  qint16 numberB;
  qint32 numberC;
  qint64 numberD;
  qint32 *intList;
  qint8 *byteList;
  DataComple *list;
  int listlen;
  QString string;
  int mode;
  float floatv;
  double doublev;
  Tree *que_chulo[1024];
};

struct Tab {
  QString name;
  DataComplex value;
};

struct Tree {
  QString name;
  Tab data[255];
  int data_n;
  Tree *branches[255];
  int branches_num;
};
    
answered by 23.12.2017 / 05:59
source