user5448913
user5448913

Reputation:

How to create a global variable using user input

I wish to create the following:

int amount[i];

As a global variable (to practice using threads and mutexes) but the variable i is defined at launch of the program:

./a.out 10

How may I take the value through the main (argv[1]) and create the global accordingly?

Upvotes: 1

Views: 7612

Answers (4)

Asish_Johney
Asish_Johney

Reputation: 11

Use constexpr keyword to make any non-const variable as constexpr. It will avoid the compiler errors, but be careful about the variable.

For example:

#include<iostream.h>

constexpr int afun()
{
  return(3);
}

enum
{

  TOTAL_NO_OF_PACKETS = afun()                      // You can use for Enum also
};


unsigned packets[afun()]; // Using in Global array

void main()
{
   // **
}

Upvotes: 1

Umamahesh P
Umamahesh P

Reputation: 1244

You can use global pointer variable and then allocate memory based on argv[1].

int *amount;

int main(int argc, char *argv[])
{
    int count = atoi(argv[1]);
    amount = malloc(count * sizeof(int));

    ...

    free(amount);
    return 0;
}

Upvotes: 5

Daniel Jour
Daniel Jour

Reputation: 16156

You're trying to use a variable length array at global scope. This won't work (globals need to have a constant, known size, otherwise compilation would be difficult).

IMHO, you shouldn't be using a global in the first place. Better use a local variable, and pass it via argument to the functions / parts of your program that need access to it.

IMHO, you shouldn't be using VLA in the first place.

I'd go with something like this:

int main(int argc, char ** argv) {
  // check arguments, not done here!
  int value = atoi(argv[1]);
  // Check that it's actually usable as a size!
  size_t count;
  if (value >= 0) {
    count = value;
  }
  else {
    // Fires of hell here
    exit(1);
  }
  int * amount = malloc(sizeof(int) * count); // add error check, please!
  // use at will
  free(amount);
  return 0;
}

If you insist on using a global, then there's the possibility to make the (constant sized) pointer amount a global variable.

Also: Using heap allocated data instead of stack allocated if you'd use a VLA is to be preferred when accessing the data from a detached thread, because the VLA could already be out of scope when the thread tries to access it!

Upvotes: 1

Jaffer Wilson
Jaffer Wilson

Reputation: 7273

It's not possible to create global variables using the user input. See basically you can use global variables by defining them in the program code.

Upvotes: 0

Related Questions