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?

6
  • 2
    std::vector is purposed for that. Commented Aug 6, 2019 at 0:29
  • new and std::vector are your friend in these types of situations. Commented Aug 6, 2019 at 0: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? Commented Aug 6, 2019 at 1:53
  • @Chipster new is probably not the OP's friend in these types of situations. Commented Aug 6, 2019 at 4: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. Commented Aug 6, 2019 at 4:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.