Blade3
Blade3

Reputation: 4360

Determining the correct size for a C++ array

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?

Upvotes: 3

Views: 278

Answers (5)

Liz Albin
Liz Albin

Reputation: 1489

There are two points in your question I'd like to cover.

  1. The actual question, how do you create the array. Johannes answered this. You use a std::vector and create it with a size allocation.
  2. Your error message. When you declare an array of some type, you must declare it with a constant size. So for example

    const int FileSize = 1000;

    // stuff

    char buffer[FileSize];

is perfectly legitimate.

On the other hand, what you did, attempting to declare an array with variable size, and then not allocating with new, generates an error.

Upvotes: 1

Hassan Syed
Hassan Syed

Reputation: 20485

You should use a std::vector and not an array.

Real arrays require you to specify their size so that the compiler can create some space for them -- this is why the compiler complains when you don't supply a constant integer. Dynamic arrays are represented by a pointer to the base of the array -- and you have to retrieve the memory for the dynamic array yourself. You may then use the pointer with subscript notation. e.g.,

int * x;
x = (int *) malloc( sizeof(int) * 
                    getAmountOfArrayElements() /* non-const result*/ 
                  );
x[5] = 10;

This leads to two types of problems:

  1. Buffer over/under flows : you might subscript-index past either end of the array.

  2. You might forget to release the memory.

Vector provides a nice little interface to hide these problems from you -- if used correctly.

Upvotes: 2

RvdK
RvdK

Reputation: 19790

Problem is that buff needs be created on the heap (instead of stack). Compiler want s to know the exact size to create on the stack.

char* buff = new char[file_size];

Upvotes: -3

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

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!

Upvotes: 10

codaddict
codaddict

Reputation: 454950

Replace

char buff[file_size];

with

char *buff = new char[file_size];

and once the use of the buff is done..you can free the memory using:

delete[] buff;

Upvotes: 1

Related Questions