Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the correct size for a C++ array

Tags:

c++

I need to be able to set the size of an array based on the number of bytes in a file.

For example, I want to do this:

// Obtain the file size.
    fseek (fp, 0, SEEK_END);
    size_t file_size = ftell(fp);
    rewind(fp);

// Create the buffer to hold the file contents.
    char buff[file_size];

However, I get a compile time error saying that the size of the buffer has to be a constant.

How can I accomplish this?

like image 596
Blade3 Avatar asked Aug 18 '26 07:08

Blade3


1 Answers

Use a vector.

std::vector<char> buff(file_size);

The entire vector is filled with '\0' first, automatically. But the performance "lost" might not be noticable. It's certainly safer and more comfortable. Then access it like a usual array. You may even pass the pointer to the data to legacy C functions

legacy(&buff[0]); // valid!
like image 160
Johannes Schaub - litb Avatar answered Aug 19 '26 23:08

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!