如何使用用户输入创建全局变量 [英] How to create a global variable using user input

查看:81
本文介绍了如何使用用户输入创建全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建以下内容:

int amount[i];

作为全局变量(用于练习使用线程和互斥锁),但是变量 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

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

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

推荐答案

您可以使用全局指针变量,然后基于argv [1]分配内存.

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

这篇关于如何使用用户输入创建全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆