Determining the correct size for a C ++ array

I need to be able to set the size of the array based on the number of bytes in the 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 should be constant.

How can i do this?

+3
source share
5 answers

Use a vector.

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

The whole vector is filled with "\ 0" first, automatically. But the performance "lost" may not be noticeable. It is certainly safer and more convenient. Then use it like a regular array. You can even pass a pointer to data in legacy C functions

legacy(&buff[0]); // valid!
+10
source

You should use std :: vector , not an array.

, - , . - . . .

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

:

  • / : .

  • , .

Vector , - .

+2

char buff[file_size];

char *buff = new char[file_size];

. , :

delete[] buff;
+1

, , .

  • , . . std::vector .
  • . - , . , ,

    const int FileSize = 1000;

    //

    char buffer [FileSize];

.

, , , , , .

+1

, buff ( ). .

char* buff = new char[file_size];
-3

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


All Articles