Home > Article > Backend Development > How Can I Declare an Array With a Variable Size in Standard C?
Dynamic Array Allocation in C with Variable Array Size
Variable-sized arrays, also known as dynamic arrays, pose a challenge in standard C. Consider the following program:
<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];<br>fseek(picture, 0, SEEK_SET); //Going to the beginning of the file<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)); */
}
The code above attempts to allocate an array of characters with a size determined by a variable siz. However, in standard C, array sizes must be constants. This poses the question: how can we declare siz correctly to allow code compilation?
Unfortunately, there is no direct method to declare an array with a variable size in standard C. However, several alternatives exist:
The above is the detailed content of How Can I Declare an Array With a Variable Size in Standard C?. For more information, please follow other related articles on the PHP Chinese website!