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....??

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;

Edited 3 Years Ago by Moschops

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.

Edited 3 Years Ago by rustysynate

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);

Edited 3 Years Ago by deceptikon

Comments
Nice tip about sizeof ;)
This article has been dead for over six months. Start a new discussion instead.