You cannot use the first syntax, it will give you a compiler error.
As for the correct approach, the answers differ depending on whether you are using C or C++.
In C++:
You should only declare the structure member in the header file.
You initialize it in the Member Initialization List in C++ source file.
Header file:
// Structure of a page
struct Page {
public:
// Number of slots
unsigned short numSlots;
void *data;
};
Source File:
Page::Page():data(malloc(PF_PAGE_SIZE))
{}
Notes:
- It is always better to use a smart pointer rather than a raw pointer.
- Also, In C++ one would usually use
new
and not malloc
but since your pointer is of the type void
, malloc
might also be fine depending on the usage.
- The code above just answers your immediate Q, There are still other important things to be considered.You still need to follow the Rule of Three since you have a pointer member with dynamic memory allocation for your structure.
In C:
In C, there are no Member Initialization lists, so you have to initialize the member after you create an object of the structure.
Header file:
// Structure of a page
struct Page {
// Number of slots
unsigned short numSlots;
void *data;
};
Source File:
struct Page obj;
obj.data = malloc(PF_PAGE_SIZE);