Home > Backend Development > C++ > How Can I Declare an Array With a Variable Size in Standard C?

How Can I Declare an Array With a Variable Size in Standard C?

Susan Sarandon
Release: 2024-11-15 22:57:03
Original
621 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">n = fread(Sbuf, sizeof(char), siz, picture);
/* ... do stuff with the buffer ... */
/* memset(Sbuf, 0, sizeof(Sbuf)); */
Copy after login

}

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:

  • std::vector: In modern C , the std::vector container can be used as a flexible alternative to arrays. It can be easily extended to any desired size and its usage is relatively straightforward.
  • New operator: The new operator can be employed to allocate memory dynamically on the heap. To create an array with a variable size, one can use char* Sbuf = new char[siz]; to allocate an array of siz characters on the heap. However, this approach introduces memory management concerns (e.g., potential memory leaks), making it less suitable than std::vector.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template