[Solved] how can I define limit of an array by the quantity of numbers put in scanf?


This example allows the user to enter numbers “indefinitely” without the need for prompting how many to enter. Of course, your computer only has so much RAM, so there is a limit, but not a practical limit. Essentially, you need to choose an initial size, then allocate more space dynamically when that size is reached.

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

#define INITIAL_SIZE 10

void printArray(const int* myArray, size_t numsEntered)
{
    for (size_t i=0; i<numsEntered; i++)
    {
        printf("myArray[%zu] = %d\n", i, myArray[i]);
    }
}

int main(void)
{
    size_t arraySize = INITIAL_SIZE;
    size_t numsEnteredSoFar = 0;
    int* myArray = malloc(sizeof(*myArray) * arraySize);  // initially make room for 10
    if (myArray == NULL) exit(-1);  // whoops, malloc failed, handle this error how you want

    while(1)
    {
        int curEntry;
        printf("enter a number, or 'q' to quit: ");
        if (scanf("%d", &curEntry) == 1)
        {
            // store in the array, increment number of entries
            myArray[numsEnteredSoFar++] = curEntry;

            // here you can check for positives and negatives, or
            // wait to do that at the end. The point of this example
            // is to show how to dynamically increase memory allocation
            // during runtime.

            if (numsEnteredSoFar == arraySize)
            {
                puts("Array limit reached, reallocing");
                // we've reached our limit, need to allocate more memory to continue.
                // The expansion strategy is up to you, I'll just continue to add
                // INITIAL_SIZE
                arraySize += INITIAL_SIZE;
                int* temp = realloc(myArray, arraySize * sizeof(*myArray));
                if (temp == NULL)
                {
                    // uh oh, out of memory, handle this error as you want. I'll just
                    // print an error and bomb out
                    fprintf(stderr, "out of memory\n");
                    exit(-1);
                }
                else
                {
                    // realloc succeeded, we can now safely assign temp to our main array
                    myArray = temp;
                }
            }
        }
        else
        {
            // the user entered 'q' (or anything else that didn't match an int), we're done
            break;
        }
    }

    // print the array just to show it worked. Instead, here you can
    // loop through and do your comparisons for positive and negative,
    // or you can continue to track that after each entry as you've
    // shown in your code
    printArray(myArray, numsEnteredSoFar);

    free(myArray);
    return 0;
}

Demo

1

solved how can I define limit of an array by the quantity of numbers put in scanf?