Module 4: Coding Basics
Structs
Declaring Structs
Declaring structures in C can be done this way.
typedef struct tagTHREADENTRY32 { (1)
DWORD dwSize;
DWORD cntUsage;
DWORD th32ThreadID;
DWORD th32OwnerProcessID;
LONG tpBasePri;
LONG tpDeltaPri;
DWORD dwFlags;
} THREADENTRY32, *PTHREADENTRY32; (2)
1 | This syntax is taken from https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/ns-tlhelp32-threadentry32 |
2 | Uses the alias THREADENTRY32 as the structure name and *PTHREADENTRY32 as a pointer to that structure. Using P is a convention from Microsoft. |
Its Rust equivalent would be.
struct THREADENTRY32 { (1)
dwSize: u32,
cntUsage: u32,
th32ThreadID: u32,
th32OwnerProcessID: u32,
tpBasePri: i32,
tpDeltaPri: i32,
dwFlags: u32,
}
Implementing Structs
Using C
typedef struct _STRUCTURE_NAME {
int ID;
int Age;
} STRUCTURE_NAME, *PSTRUCTURE_NAME;
int main(int argc, char *argv[])
{
STRUCTURE_NAME struct1 = { 0 }; (1)
struct1.ID = 6969;
struct1.Age = 420;
STRUCTURE_NAME struct2 = { .ID = 6969, .Age = 420}; (2)
PSTRUCTURE_NAME structpointer1 = &struct1; (3)
structpointer1->Age = 421;
(*structpointer1).Age = 422; (4)
return 0;
}
1 | Initializes all elements to 0. |
2 | Specifically initializes the elements. No need to specify all elements. |
3 | Creates a pointer to the struct which can be accessed with → . |
4 | An alternative to accessing pointer values. This is called Dereferencing Pointers. |