"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to declare variable size arrays in standard C?

How to declare variable size arrays in standard C?

Posted on 2025-04-15
Browse:308

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:

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:

  • 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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3