Is it possible to declare an array with a variable as its index value, so that the user himself/herself can enter the exact number of items required....??

Dani AI

Generated

Short answer: yes — an array size can come from a variable, but the right technique depends on language, lifetime and safety. correctly points out that modern C can use runtime-sized arrays and that older C needs heap allocation; demonstrates a variable-length array (VLA) in C; highlights a safer malloc idiom and fixes the free usage. The practical choice should be driven by how large or untrusted the user-provided size can be and whether automatic cleanup is required.

Tradeoffs and cautions: VLAs live on the stack, so they are fine for small, short-lived buffers but dangerous if the user can request a very large size (stack overflow). VLAs are a C feature (compiler support can vary) and are not part of standard C++; relying on them reduces portability. Heap allocation avoids stack limits but requires explicit checks (validate the size, guard against integer overflow when computing bytes, and always check the allocation result).

Recommended patterns:

// C++: prefer an owning container with RAII
size_t n = /* parsed from input */;
std::vector<int> v(n);   // automatically allocated and freed

For C, prefer heap allocation with explicit validation and limits, use realloc for resizing when appropriate, and always match allocation and deallocation (malloc⇄free, new[]⇄delete[]). Sanitize and cap user input (impose a sensible maximum) to prevent accidental or malicious large allocations.

Extra tips: prefer zero-initialized allocations when default values matter, use tools like AddressSanitizer/Valgrind to catch leaks or invalid accesses, and favor high-level containers (std::vector or smart pointers) where possible to avoid manual memory-management errors.

Recommended Answers

All 3 Replies

Yes.

If your C compiler is quite modern (C99 or later, you can just use them as normal). If your C compiler is earlier, you must use dynamic memory. Here are examples in C++ and C.

C++

int i;
cin >> i;

int* array = new int[i];  // an array of size i has now been created.

You must also remember to release memory allocated using new yourself, with delete, when you are finished using it.

delete[] array;

This sort of thing is a pain and in C++ we have containers such as vector to do all this for us. Use a vector or some other container unless you have a really good reason not to.

C

int i;
...
// code here to get value of i from the user
...
int *array = malloc(i*sizeof(int));  // alloc enough memory for the array

You must also remember to release memory allocated using malloc yourself, with free, when you are finished using it.

free array;

Yes, it is possible but it is not recommended. Consider the following program.

    #include <stdio.h>

    int main()
    {
        int n=10;
        int i;
        int a[n];
        for (i=0;i<10;i++)
        {
            a[i]=i;
        }
        printf ("%d", a[5]);
        return 0;
    }

It will produce the desired result which is 5.

NOTE: The value of n should be know before the statement int a[n]; is executed.
It is also possible to get the value of n from the user before the statement int a[n];

It is better to have dynamically allocated array in this case.

Yes, it is possible but it is not recommended.

Why?

It is better to have dynamically allocated array in this case.

Again, why? Please assume that the compiler supports C99, since the obvious "it's not portable" prior to C99 is obvious.

int *array = malloc(i*sizeof(int)); // alloc enough memory for the array

A cleaner way to do this without listing the type twice is by using a quirk of the sizeof operator:

int *array = malloc(i * sizeof *array);

Because sizeof doesn't evaluate the expression given as an operand, you're not dereferencing the (at this point) uninitialized pointer. It's not so big of a deal in cases where you're declaring and allocating all in one statement, but consider cases where the type changes and you do the allocation elsewhere. Then you'd need to grep the code looking for any instance of sizeof(int) in reference to that variable and change the type.

free array;

free() is a function:

free(array);
commented: Nice tip about sizeof ;) +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.