How to create a global variable using user input
Asked Answered
S

4

1

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?

Sardella answered 2/3, 2016 at 10:30 Comment(3)
why a global ? why not a pointer to the array created in the main ?Altostratus
static class variable can't use VLA.Idolatrize
You cannot create a global VLA. So, Use int* amount; int main(int argc, char** argv){ amount = malloc(atoi(argv[1]) * sizeof(int)); etc and free it at the end of main. I leave error checking upto you.Katrinka
D
5

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;
}
Decencies answered 2/3, 2016 at 10:45 Comment(0)
M
1

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!

Manipulator answered 2/3, 2016 at 10:44 Comment(0)
H
1

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()
{
   // **
}
Herat answered 9/3, 2021 at 15:19 Comment(0)
P
0

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.

Pettiford answered 2/3, 2016 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.