Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading