I am trying to represent a HD page in a struct. The code below does not work, because page_size is not a constant.
int page_size = 4096;
struct page {
char data[page_size];
/* some methods */
}
Since I am building and randomly accessing arrays of pages, it would be nice if I could treat a page as a fixed length struct of size page_size. If possible, I would like to read page_size from a configuration file at the start of the program, or get it from the OS (e.g., GetDiskFreeSpace() on Windows). Obviously, there are only a handful of realistic page sizes, but I can’t think of a way to exploit that.
Any help is appreciated.
Frank
Nope. As you’ve found out, you can’t. The compiler needs to know the size of its data structures, reliably and constantly, to do its work.
I’m assuming that the page data is not the only content of your
struct. You probably have some header / management information about your page in there along with the text.The common solution would be for your struct to contain a
char *pointing at the actual text. That text could then be in a chunk of memorymalloc()‘d orcalloc()‘d to whatever size you need. Alas, this means you’ll have to remember to move the external text around along with your struct whenever you do operations that move the struct around, and memory manage the text when you get rid of the struct… the usual C headaches.EDIT
There are sensible “standard” ways to do this kind of thing. Here is a suggestion:
Now you can treat page_pointers as an array of pages, doing stuff like
or
You have an overhead of one pointer per page (surely acceptable), and your pages are physically contiguous in memory. What more could you ask? 🙂