0

Suppose I have to input an array but I don't know the size of tha array.If I know the size of the array I can do like this

for(i=0;i<n;i++)
  scanf("%d",&arr[i]);

This can be done if I know the value of n. What if I don't know the value of n? How can we input the array?

4
  • 2
    You may allocate a fixed size at the beginning, and use realloc when the array is full. Commented Jun 11, 2020 at 14:05
  • Do you know what the maximum value of n may be? If so, allocate an array of this size. Commented Jun 11, 2020 at 14:09
  • 1
    Best thing is to ask for the size as a first input. Commented Jun 11, 2020 at 14:09
  • Your question title says you want to create an array of variable size, but your question asks for a way to input data in all elements of an fixed size array but you just don't know the size of it. What do you mean of them both? Commented Jun 11, 2020 at 15:29

4 Answers 4

3

Here is an example showing one way to manage a dynamic array.

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
    /*  To manage an array of varying size, we keep a pointer to the first 
        element of the array and the number of elements in the array.

        The pointer is initially null, and there are no elements in the array.
    */
    int *Numbers = NULL;
    size_t NumberOfAllocatedElements = 0;

    /*  We get numbers one by one, using TemporaryNumber to hold them.  As long
        as scanf reports it was able to read and assign 1 item, we continue
        adding the number to the array.
    */
    int TemporaryNumber;
    while (1 == scanf("%d", &TemporaryNumber))
    {
        /*  To grow the array, increase the number of allocated elements and
            use realloc to request more space.
        */
        int *NewNumbers =
            realloc(Numbers, ++NumberOfAllocatedElements * sizeof *NewNumbers);

        /*  If realloc fails, we report an error and exit.  A more
            sophisticated program could do something else in this case.
        */
        if (!NewNumbers)
        {
            fprintf(stderr, "Error, unable to allocate memory.\n");
            exit(EXIT_FAILURE);
        }

        //  Update our pointer with the new address.
        Numbers = NewNumbers;

        //  Record the new element in the array.
        Numbers[NumberOfAllocatedElements - 1] = TemporaryNumber;
    }

    //  Show the contents of the array.
    for (size_t i = 0; i < NumberOfAllocatedElements; ++i)
        printf("Number %zu is %d.\n", i, Numbers[i]);

    //  Release the memory.
    free(Numbers);
}

This is largely a beginner example. An improvement would be to allocate large amounts of memory at a time, instead of just one more element each time. In this case, the program then needs to track two numbers about the array: The amount of space allocated and the number of elements currently used in it.

A variety of alternatives are also possible.

Sign up to request clarification or add additional context in comments.

Comments

1

You can create a dynamic array by following the answer to this question. It uses a structure that contains the array, its max size and its used size. If the max size is reached, the array will be reallocated and the max size increased.

Comments

0

Solution 1: If you don't know the size of the array at either run-time or compile-time, you should go with linked lists

Solution 2: As Jean-Claude mentioned in his comment, Declare a fixed-size array using dynamic memory allocation functions like malloc() or calloc() and realloc() the size of array when needed.

Code for Solution 2:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *p = NULL, i = 0, j = 0;

    // Fixed-size array of size 1.
    if( (p = (int *) malloc (1 * sizeof(int)) ) == NULL)
    {
        printf("Memory Unavailable.\n");
        exit(1);
    }

    // Sentinel-loop and reallocation for the array.
    do
    {
        printf("Enter value\n-999 to end: ");
        scanf("%d", &p[i]);
        if( p[i] == -999)
            break;
        i++;
        if((p = (int *)realloc(p, sizeof(int)*(i+1))) == NULL)
        {
            printf("Memory can't be reallocated.\n");
            exit(2);
        }
    }
    while(1);

    printf("\nElements of the array:\n");
    for( ; i >= 0; i--)
        if(p[j] != -999)
            printf("%4d", p[j++]);
    free(p);
    return 0;
}

Output:

Enter value
-999 to end: 1
Enter value
-999 to end: 2
Enter value
-999 to end: 3
Enter value
-999 to end: 4
Enter value
-999 to end: 5
Enter value
-999 to end: -999

Elements of the array:
   1   2   3   4   5

Comments

0

I would love to know if you are using a user interface where you can take the array size as input and then proceed normally as if you knew the size of the array in advance.

Some code sample for you to follow : -


    int reqArraySize;
    printf("Enter the array size: ");
    scanf("%d", &reqArraySize);

  

After this you may proceed with this interger input array size :


    for(i=0;i<reqArraySize;i++)
      scanf("%d",&arr[i]);

Hope this helps you.

Cheers.

1 Comment

Well, you missed the most important part - the array allocation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.