Typedef struct with pointer

Hi all,

what does it mean, that after a typedef struct, after the custom name for it, there is also a pointer? Heres an example:

1
2
3
4
5
6
7
8
typedef struct tagPAINTSTRUCT {
  HDC  hdc;
  BOOL fErase;
  RECT rcPaint;
  BOOL fRestore;
  BOOL fIncUpdate;
  BYTE rgbReserved[32];
} PAINTSTRUCT, *PPAINTSTRUCT;


I know why PAINTSTRUCT is there, but what is *PPAINTSTRUCT doing there?

Ty in advance!
It means PPAINTSTRUCT is the name (typedef) of a pointer to a tagPAINTSTRUCT.
So i actually declare two things, specifically, PAINTSTRUCT is the name (typedef) of a tagPAINTSTRUCT and additionally in this example, PAINTSTRUCT is the name (typedef) of a pointer to a tagPAINTSTRUCT, right?
No, note the extra P at the beginning of PPAINTSTRUCT. If you change your phrase "PPAINTSTRUCT is the name (typedef) of a pointer to a tagPAINTSTRUCT", then yes, you're right.
You actually declare three things, tagPAINTSTRUCT, PAINTSTRUCT, and PPAINTSTRUCT. You should never do this in C++ as it is bad practice, but it's needed for some things in C.
Actually, I never understood why that is necessary.
I'm not sure why this is considered bad practice in C++, but I'll take L B's word for it for now.

This is done because in C you are required to use the struct keyword when declaring variables. Example:

1
2
3
4
5
6
7
struct MyStruct
{
    int myValue;
}

//This declaration MUST include the struct keyword in C (but not int C++).
struct MyStruct myVariableOfTypeMyStruct;


So that justifies the first typedef (the one that defines PAINTSTRUCT in your example). With the typedef you can just omit the keyword. The other name, PPAINTSTRUCT in your example, is just a declaration of a pointer type of the same structure. In summary, the whole thing is the same as this:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct tagPAINTSTRUCT {
  HDC  hdc;
  BOOL fErase;
  RECT rcPaint;
  BOOL fRestore;
  BOOL fIncUpdate;
  BYTE rgbReserved[32];
};

typedef struct tagPAINTSTRUCT PAINTSTRUCT;
typedef PAINTSTRUCT *PPAINTSTRUCT;
//Alternatively, you can do the last one like this:
typedef struct tagPAINTSTRUCT *PPAINTSTRUCT;
Yeah, I knew that (but the OP probably not, so, good explanation). I just don't understand why would it be necessary.

typedef struct tagPAINTSTRUCT {
HDC hdc;
BOOL fErase;
RECT rcPaint;
BOOL fRestore;
BOOL fIncUpdate;
BYTE rgbReserved[32];
} PAINTSTRUCT, *PPAINTSTRUCT;


I can think of 2 reasons why C programs have above syntax. One is perhaps to give C programmers what C++ programmers have in their classes syntax.

e.g
class PAINTSTRUCT {

};

PAINTSTRUCT a; //C++ program

typedef ....{

} PAINTSTRUCT;
PAINTSTRUCT a; //C program

The other I can think of is not so useful but I guess is if next time you should change the typedef name, your existing program no need any code changes as they always point to PAINTSTRUCT.

typedef tagPAINTSTRCUT { //next time change to tagABC for e.g

} PAINTSTRUCT;



Topic archived. No new replies allowed.