I have a structure that contains a pointer to a fixed sized memory.
Say,
// Structure of a page
struct Page {
public:
// Number of slots
unsigned short numSlots;
void *data = malloc(PF_PAGE_SIZE);
};
I want to put this declaration in a header file. Should I also explicitly put the malloc part in it or it should only contain void *data and no details about how much memory the pointer points to?
In short should the declaration look like above or resemble the following:
// Structure of a page
struct Page {
public:
// Number of slots
unsigned short numSlots;
void *data;
};
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:
Source File:
Notes:
newand notmallocbut since your pointer is of the typevoid,mallocmight also be fine depending on the usage.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:
Source File: