Reputation: 2399
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;
};
Upvotes: 0
Views: 81
Reputation: 206528
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++.
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:
new
and not malloc
but since your pointer is of the type void
, malloc
might also be fine depending on the usage.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);
Upvotes: 1