Search code examples
cmallocrealloc

Is there a way to discard a number stored using malloc/realloc when printing the result?


What the code does:

  1. Asks the person to enter x amount of numbers and finishes by entering a " 0 " (zero).
  2. The numbers are then saved and stored using malloc/realloc.
  3. With the help of a bubble sort, numbers entered will be sorted and printed out in an ascending order.

My problem: when the sorted numbers are printed out, it also adds the 0 (zero), which only purpose is to finish the task and not be added to the list of numbers entered by the person. For example if I add: 4,5,8,1,3,1,10 ("0" to finish). The printing result will be: 0, 1, 1, 3, 4, 5, 8, 10.

I'm new to C (worked with it for only about 2 weeks). So far I've tried changing " i " to 1 in this for-loop. However, all it does is to basically shift everything one step (?). Causing the 0 only to go from being first to last: 1, 1, 3, 4, 5, 8, 10, 0.

> //Bubble sort:
>         for (int i = 0; i < inputNumber; i++)

I assume using free() will only work when you're looking to free all the memory stored and not one particular number? Any help is appreciated. Further, yes this is a work assignment :).

Here's the code:

int main()
{
    int nr = 1;
    int temp;
    int *numberStore = malloc(sizeof(int));
    int inputNumber = 0;

    while (nr != 0)
    {
        printf("Add numbers to be stored (finish by entering 0): ");
        scanf("%d", &nr);
        printf("\n");
        numberStore[inputNumber] = nr;
        inputNumber++;
        numberStore = realloc(numberStore, (inputNumber + 1) * sizeof(int));
    }

    //Bubble sort:
    for (int i = 0; i < inputNumber; i++)
    {
        for (int j = 0; j < (inputNumber - i - 1); j++)
        {
            if (numberStore[j] > numberStore[j + 1])
            {
                temp = numberStore[j];
                numberStore[j] = numberStore[j + 1];
                numberStore[j + 1] = temp;
            }
        }
    }

    //Prints the stored numbers in ascending order:
    for (int i = 0; i < inputNumber; i++)
    {
        printf("%d\n", numberStore[i]);
    }

    return 0;
}

Solution

  • Just simply don't add 0 to your data

    while (nr != 0)
    {
        printf("Add numbers to be stored (finish by entering 0): ");
        scanf("%d", &nr);
        printf("\n");
        if (nr != 0)                // only add if not 0
        {
            numberStore[inputNumber] = nr;
            inputNumber++;
            numberStore = realloc(numberStore, (inputNumber + 1) * sizeof(int));
        }
    }
    

    Or, same idea, slightly more compact: if (nr == 0) break;