0

Here is the program:

int siz = 0;
int n = 0;
FILE* picture;

picture = fopen("test.jpg", "r");
fseek(picture, 0, SEEK_END);
siz = ftell(picture);

char Sbuf[siz];
fseek(picture, 0, SEEK_SET); //Going to the beginning of the file
while (!feof(picture)) {
    n = fread(Sbuf, sizeof(char), siz, picture);
    /* ... do stuff with the buffer ... */
    /* memset(Sbuf, 0, sizeof(Sbuf)); 
}

I need to read the file size. I know for sure that this code compiled on another compiler. How to correctly declare siz correctly so that the code compiles?

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 2
    `std::vector` is purposed for that. – πάντα ῥεῖ Aug 06 '19 at 00:29
  • [`new`](https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/) and [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) are your friend in these types of situations. –  Aug 06 '19 at 00:30
  • I assume you are using Sbuf as an array with bytes of the image, wouldn't using `unsigned char` instead of the `char` be better? – Marcin Poloczek Aug 06 '19 at 01:53
  • @Chipster `new` is probably not the OP's friend in these types of situations. – L. F. Aug 06 '19 at 04:09
  • @L.F. Fair enough. My thought was it was a way to create a variable length array if they really needed an array type thing and couldn't settle for something like a `std::vector`. I fully agree there are much better options. –  Aug 06 '19 at 04:11
  • Does this answer your question? [Define array, then change its size](https://stackoverflow.com/questions/3851181/define-array-then-change-its-size) –  Nov 25 '19 at 23:07

2 Answers2

4

There is no proper way to do this, as a program with any variable length array is ill-formed.

An alternative, so to speak, to a variable length array is a std::vector:

std::vector<char> Sbuf;

Sbuf.push_back(someChar);

Of course, I should mention that if you are using char specifically, std::string might work well for you. Here are some examples of how to use std::string, if you're interested.

The other alternative to a variable length array is the new operator/keyword, although std::vector is usually better if you can make use of it:

char* Sbuf = new char[siz];

delete [] Sbuf;

However, this solution does risk memory leaks. Thus, std::vector is preferred.

1

You can dynamically create an array using new keyword:

char* Sbuf; // declare a char pointer Sbuf
Sbuf = new char[siz]; // new keyword creates an array and returns the adress of that array

delete Sbuf; // you have to remember to deallocate your memory when you are done

Better, more standard compatible approach would be to use smart pointers

std::unique_ptr<char[]> Sbuf = std::make_unique<char[]>(siz);
Marcin Poloczek
  • 923
  • 6
  • 21