Can I use a variable to indicate the size of an array of struct elements?

I am trying to represent an HD page in a frame. 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 create and arbitrarily access arrays of pages, it would be nice if I could consider the page as a structure with a fixed page_size page length. If possible, I would like to read page_size from the configuration file at the beginning of the program or get it from the OS (for example, GetDiskFreeSpace () on Windows). Obviously, there are only a few realistic page sizes, but I can't figure out how to use this.

Any help is appreciated.

Franc

+3
source share
6

. , . , , .

, struct. , / .

, char *, . malloc() 'd calloc()' d , . , , , , , , ... C .


"" . :

typedef char *page_ptr;
int page_size = discover_page_size();
int max_page_count = discover_max_page_count();
int pages_stored = 0;
page_ptr *page_pointers = calloc(max_page_count, sizeof(page_ptr));
char *pages = calloc(max_page_count * page_size, sizeof(char));
page_pointers[0] = pages;
int i;
for (i=1; i<max_page_count; i++) {
    page_pointers[i] = page_pointers[i-1] + page_size;
}

page_pointers , ,

read(filedesc, page_pointers[page_count++], page_size);

memmove(page_pointers[69], page_pointers[42], page_size);

(, ), . ?:)

+4

{C++}

, std::vector?

int page_size = 4096; //or any variable

class page{

    std::vector<char> PAGE;
    public:

    page():PAGE(page_size){}
};
+2

[++]

:

int page_size = 4096;

struct page 
{
    char *pData;
    page() : pData(new char[page_size])
    {
    }
    ~page()
    {
        delete[] pData;
    }

  /* some methods */
}

.

+1

C ++ , . C99 C, , .

0

, , , ,

struct page {

  std::string data;

  /* some methods */
}

C ++, C.

0

#define PAGE_SIZE 4096

struct page {

  char data[PAGE_SIZE];

  /* some methods */
}

, PAGE_SIZE

-1

Source: https://habr.com/ru/post/1754957/


All Articles