0

I want to create multiple variables, like P0, P1, and P2. The range will be given by the user. How can I solve this in C?

2 Answers 2

0

Can you dynamically create a number of variables dynamically at runtime based on input from a user at runtime? It's possible, but not directly in the way that you're describing.

Memory can be allocated dynamically at runtime using techniques like linked lists (taught later in the class) or perhaps by creating an array with a maximum number of elements defined in the program code (i.e., a maximum number of elements), or given as a parameter or a var before creating the array. Here's an example:

#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>

int main(void)
{
    int i = get_int("Int?  ");
    int array[i];

    for(int j = 0; j<i; j++)
    {
        array[j] = j;
        printf("array[%i] = %i\n",j,j);
    }
}

However, I know of no way to create and name vars like p1, p2, ... pn dynamically.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

0

welcome to the forum. Be sure to get your first badge by taking the tour.

Here's a sneak peak:

CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50.

This does not sound like a question from the CS50 courseware. This is a great course, and if you are interested in learning C, I strongly recommend it. You can sign up here at edx.org. There is an option to audit the course. You won't get a certificate, but it is free. You will learn the same amount.

C is a strongly typed language, and as such it is not possible to create variable names dynamically. You might be able to accomplish the same thing by using an array, which you could allocate based on a user input.

3
  • Dino, I think I disagree. This is a basic question about C, which is the first 2/3 of the course. I can think of several places where this could come into play, although I wouldn't recommend this technique when other, better ones exist. Still, it's good to know the answer to the question. ;-)
    – Cliff B
    Commented Aug 30, 2018 at 22:58
  • @CliffB Agree to disagree. Thanks for not downvoting :) Commented Aug 31, 2018 at 1:49
  • Fair enough to agree to disagree. I didn't downvote because your answer contains significant, useful information! Downvotes are for bad info. ;-)
    – Cliff B
    Commented Aug 31, 2018 at 2:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .