3

I'm a beginner in C and I came across some codes in a header file that I'm not sure what style it uses and what it means.

typedef struct tActiveObject *testActiveObjectPtr;

typedef struct tActiveObject {
    ActiveObject ao;
    int state;
} testActiveObject, *testActiveObjectPtr;

Why do we need to create a pointer as an alias i.e. testActiveObject and *testActiveObjectPtr? And is this just some C style that I am not aware of?

Thanks.

gmgn
  • 33
  • 2
  • Possible duplicate of: http://stackoverflow.com/questions/1543713/c-typedef-of-pointer-to-structure Please refer to tristopia's answer, I hope it explains what you need to know. – Paweł Duda Mar 10 '15 at 02:00
  • 1
    @PawełDuda Nah, not a duplicate, since that link doesn't explain the first typedef, or the struct tag etc. In fact this code doesn't make any sense at all, see my answer below. – Lundin Mar 10 '15 at 07:42
  • @PawełDuda Thanks, but that answer only solve my question partially. Still helps me to understand the situation better though. – gmgn Mar 10 '15 at 15:48

1 Answers1

1

If the both those typedefs occur in the same header file, then the code doesn't make any sense. In that case, the first typedef is completely superfluous and the whole code could get replaced with

typedef struct {
    ActiveObject ao;
    int state;
} testActiveObject, *testActiveObjectPtr;

Otherwise if the typedefs were in different files, the code might have been a failed attempt to create a pointer to an incomplete type, but it doesn't look like that's the case. The struct tag is superfluous, but also smells like a failed attempt to create a self-referencing struct.

Also, good programming practice dictates that you never hide a pointer behind a typedef.

So it would seem the whole code was created by a rather confused person who didn't quite know what they were doing. If possible, throw the code away and replace it with:

typedef struct {
    ActiveObject ao;
    int state;
} testActiveObject,

...

testActiveObject* ptr; // whenever you need a pointer to this type
Lundin
  • 195,001
  • 40
  • 254
  • 396