如何使用用户输入创建全局变量

How to create a global variable using user input

我想创建以下内容:

int amount[i];

作为全局变量(练习使用线程和互斥量)但变量 i 是在程序启动时定义的:

./a.out 10

如何通过 main (argv[1]) 获取值并相应地创建全局?

无法使用用户输入创建全局变量。看到基本上你可以通过在程序代码中定义它们来使用全局变量。

您正在尝试在全局范围内使用可变长度数组。这行不通(全局变量需要有一个常数,已知大小,否则编译会很困难)。

恕我直言,您一开始就不应该使用全局变量。最好使用局部变量,并通过参数将其传递给需要访问它的函数/程序部分。

恕我直言,您一开始就不应该使用 VLA。

我会选择这样的东西:

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;
}

如果您坚持使用全局变量,则可以将(恒定大小的)指针 amount 设为全局变量。

另外:当从分离线程访问数据时,如果您使用 VLA,最好使用堆分配数据而不是堆栈分配数据,因为当线程尝试访问数据时,VLA 可能已经超出范围它!

可以使用全局指针变量,然后根据argv[1]分配内存。

int *amount;

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

    ...

    free(amount);
    return 0;
}

使用 constexpr 关键字使任何非常量变量成为 constexpr。它将避免编译器错误,但要注意变量。

例如:

#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()
{
   // **
}