Search code examples
cuser-inputdynamic-memory-allocation

User input and dynamic memory allocation in C


I'm still fairly new to C programming and I've been trying to create a program which needs user input first. In the beginning, I need the user to input certain amount of numbers such as: 4 12 8 6 5 4 7

So basically, he keeps on entering numbers, making spaces in between them. The user then presses enter and that is the end of user input. Reading up on the stuff I've already found online, I've seen this posted:

while (...){
      scanf("%c",&c[i]);
         if(c[i]=='\n')
            break;
}

So, now, using the dynamic memory allocation, is it possible to let the user enter everything in one line like this, separated by spaces, then ending it once he presses enter?

What I want to happen:

  • user input: 5 4 5 6 8 5 enter
  • array = {5, 4, 5, 6, 8, 5}

Solution

  • You said: certain amount of numbers; do you know that number upfront? If yes - you can allocate memory for that many values. If not - you'd need to implement some logic to allocate additional storage as needed. For example by doubling the already allocated space. You can increment the capacity by one to avoid wasted space, at the cost of repeated copying of your data.

    #define  _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      char ch = 0;
      int size = 0, capacity = 1;
      int* c = malloc(sizeof(int) * capacity);
      while (1) {
        scanf("%d%c", &c[size], &ch);
        if (ch == '\n')
          break;
        size++;
        if (size == capacity)
        {
          capacity *= 2; // use whatever policy to increase the capacity
          c = realloc(c, sizeof(int) * capacity);
        }
      }
      return 0;
    }