Home > Article > Backend Development > How Can I Create Dynamically Sized Arrays in C to Handle Files of Unknown Size?
Dynamically Sized Arrays in C Language
Consider the following C code:
<br>int siz = 0;<br>int n = 0;<br>FILE* picture;</p> <p>picture = fopen("test.jpg", "r");<br>fseek(picture, 0, SEEK_END);<br>siz = ftell(picture);</p> <p>char Sbuf[siz]; // Error: Variable-length array<br>fseek(picture, 0, SEEK_SET);<br>while (!feof(picture)) {</p> <pre class="brush:php;toolbar:false">n = fread(Sbuf, sizeof(char), siz, picture); // do stuff with the buffer // memset(Sbuf, 0, sizeof(Sbuf));
}
In this code, the goal is to read the contents of a file into a buffer, but the size of the buffer is unknown until the file is opened and its size is determined. However, C language does not allow declaring arrays with variable lengths.
Alternatives to Variable-Length Arrays
To address this issue, there are several alternatives:
<br>std::vector<char> Sbuf;</li></ul> <p>Sbuf.push_back(someChar);<br>
<br>char* Sbuf = new char[siz];</li></ul> <p>delete [] Sbuf; // Deallocate memory when done<br>
Considerations
While dynamic allocation provides a way to create a variable-sized array, it comes with some caveats:
Conclusion
Although variable-length arrays are not supported in C, there are several alternative approaches available to create dynamic arrays that can adapt to the size of the data to be stored. It is essential to choose the most appropriate option based on the specific requirements and constraints of the project.
The above is the detailed content of How Can I Create Dynamically Sized Arrays in C to Handle Files of Unknown Size?. For more information, please follow other related articles on the PHP Chinese website!