Home >Backend Development >C++ >How Can I Declare a Run-Time Sized Array in C without Dynamic Memory Allocation?

How Can I Declare a Run-Time Sized Array in C without Dynamic Memory Allocation?

DDD
DDDOriginal
2024-12-20 14:08:17675browse

How Can I Declare a Run-Time Sized Array in C   without Dynamic Memory Allocation?

Array Size at Run Time without Dynamic Allocation: A C99 Innovation

In C , the notion of declaring an array with a size determined at run-time often raises concerns. However, a recent encounter with a peculiar code snippet has sparked the question: how can an array be declared without dynamic allocation, yet have its size specified at run-time?

Consider the following C code:

int main(int argc, char **argv)
{
    size_t size;
    cin >> size;
    int array[size];
    for (size_t i = 0; i < size; i++)
    {
        array[i] = i;
        cout << i << endl;
    }

    return 0;
}

Compilers such as GCC have adopted a feature from C99 that allows variable-sized arrays. This innovative feature enables arrays to be declared on the stack with a size that can be determined during execution. However, unlike dynamic allocation with new or malloc, variable-sized arrays allocate memory on the stack, similar to declaring an array with a fixed size.

Variable-sized arrays offer a performance advantage over dynamic allocation as they avoid the overhead of heap memory management. By allocating memory on the stack, these arrays reduce the chances of memory fragmentation and enhance program performance.

It's important to emphasize that this feature is unique to C99 and is not supported in older versions of the C language. Therefore, if you encounter code that relies on variable-sized arrays, ensure that you compile it with a C99-compliant compiler to avoid storage size errors.

The above is the detailed content of How Can I Declare a Run-Time Sized Array in C without Dynamic Memory Allocation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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