Consider the following code snippet:
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 ... */ }
In this code, we aim to read the size of the file "test.jpg" and create an array Sbuf to store its contents. However, the size of Sbuf is determined dynamically, based on the file's size. This raises the question: how can we correctly declare siz so that the code compiles successfully?
Unfortunately, there is no straightforward way to create an array with a variable length in C. Variable length arrays, also known as flexible arrays, are not a part of the C standard. Consequently, the code presented above will not compile correctly.
There are several alternative solutions to this problem, each with its own pros and cons:
std::vector is a standard library container in C that provides a dynamic array-like data structure. It automatically allocates and reallocates memory as needed, eliminating the need to manually declare the array size. The following code demonstrates how to use std::vector in this scenario:
std::vector<char> Sbuf; Sbuf.push_back(someChar);
Another option is to use the new operator to allocate memory dynamically for the array. However, this approach requires manual memory management, increasing the risk of memory leaks. Additionally, it is generally recommended to use std::vector over direct memory allocation for dynamic arrays.
char* Sbuf = new char[siz]; // ... delete [] Sbuf;
Certain external libraries, such as the GNU C Library (glibc), provide support for variable length arrays. However, this functionality is non-standard and may not be supported on all compilers and platforms.
The above is the detailed content of How Can You Correctly Declare an Array with a Dynamic Size in C?. For more information, please follow other related articles on the PHP Chinese website!