Home > Net >  Creating 'n' number of variables, where 'n' is an input from the user
Creating 'n' number of variables, where 'n' is an input from the user

Time:09-15

I am beginner in C language. Just wanted to know if there's a way of creating 'n' number of variables, where 'n' is an input from the user. Is it possible to decide the number of variables to be created during runtime.

CodePudding user response:

Is it possible to decide the number of variables to be created during runtime.

If we are talking about creating more or less variables depending on user input, that would mean something like this:

   int n;
   int result = scanf("%d", &n);
   // TODO: Check result value.

   int var0, var1, var2, ... varn;

This is not possible. Each variable you want to use, must de defined in your code at compile time.

If you think about "number of variables" in the way of "room for a number of values" then we can do something for you.

In C99 a feature called "Variable Length Arrays" (VLA) was introduced. (In C11 it was made optional)

This feature allows you to define a local array variable with a non-constant number of elements:

   int n;
   int result = scanf("%d", &n);
   // TODO: Check result value; check n for allowed range to fit into stack

   int values[n];

The memory for this array is released when you leave the function where you defined it.

Or in all C standards you can use a pointer to a dynamically allocated memory:

   int n;
   int result = scanf("%d", &n);
   // TODO: Check result value.

   int *values = malloc(n * sizeof(*values));
   // TODO: Check for NULL value.

You can use this memory also after leaving the function where you allocate it. And you must free it later if you don't need it anymore.

In both versions you can access the values via array notation: value[index].

  • Related