Is there any way to create an array until user enters a specific number?

Viewed 79

When we create an array with unknown size then we use malloc() function.

Here is the code when I want to take the array size from user as an input.

int* ptr, len;
printf("Please enter the size number:");
scanf_s("%d", &len);

ptr = (int*)malloc(len * sizeof(int));

for (int i = 0; i < len; i++)
    {
        printf("Enter the %d. number: ", i+1);
        scanf_s("%d", ptr + i);
    }

But here is the question I want to build an application where user doesn't indicate any size value and enters the numbers so that place them into an array. Array is filling but hasn't got any limits. It hasn't allocated any memory initially like my code above. Only limit is that user enters a specific number (say -5) then, array is being stopped. And prints out the values.

In essence: I am looking for memory allocation but allocation will be decided on specific user input.

Realloc edit that runs the code infnitely and never displays the array

int i = 0,ctr=0;
int* ptr = (int*)malloc(sizeof(int));
do
{
    printf("Enter the %d. value: \n",i+1);
    scanf_s("%d", ptr + i);
    ctr += 1;
    ptr = (int*)realloc(ptr, (i + 2) * sizeof(int));
    i += 1;
} while (*(ptr+i)!=-1);
2 Answers

This worked for me.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *ptr,n;
    ptr = (int *)malloc(sizeof(int)); // 
    int i = 0;
    while(1)
    {
        puts("Enter a number");
        scanf(" %d",&n);// Take the value
        if(n == -5) //
        {
            *(ptr + i) = n; //if you don't wish to add -5 to your array remove this 
                // statement and following i++
            i++;
            break;
        }
        else
        {
            *(ptr + i) = n;
            ptr = realloc(ptr,(i+2)*sizeof(int));// reallocating memory and 
                           // passing the new pointer as location in memory can 
                            // change during reallocation.
            i++;
        }
    }
    int end = i;// Saving the number of elements.
    for(i=0;i<end;i++)
        printf(" %d\n",ptr[i]);
    return 0;
}

You can use the standard function realloc or define a list. In the last case the access to elements of a list will be sequantil.

Here is a demonstrative program that shows how the function realloc can be used to enter a sequence of numbers terminated by a sentinel value.

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

int main( void )
{
    int *p = NULL;
    size_t n = 0;

    int allocation_failed = 0;
    const int Sentinel = -1;

    printf( "Enter a sequence of values (%d - exit): ", Sentinel );

    for (int value; !allocation_failed         &&
                    scanf( "%d", &value ) == 1 &&
                    value != Sentinel; )
    {
        int *tmp = realloc( p, ( n + 1 ) * sizeof( *p ) );

        if (!( allocation_failed = tmp == NULL ))
        {
            p = tmp;
            p[n++] = value;
        }
    }

    for (size_t i = 0; i < n; i++ )
    {
        printf( "%d ", p[i] );
    }

    putchar( '\n' );

    free( p );
}

The program output might look like

Enter a sequence of values (-1 - exit): 0 1 2 3 4 5 6 7 8 9 -1
0 1 2 3 4 5 6 7 8 9

Pay attention to that you may not use the same pointer in a call of realloc like for example

int *p = realloc( p, ( n + 1 ) * sizeof( *p ) );

because in general the function realloc can return a null pointer. In this case the address of the already allocated memory will be lost due to reassigning the pointer p will a null pointer.

Related