是否可以在启动时根据用户输入设置全局变量或定义?

Is it possible to set a global variable or a define from the user input at launch time?

我正在编写一个模拟程序,假设用户输入一个整数来定义参与模拟的人数,我需要使用相同的输入来设置一对全局变量。 我尝试了以下版本和其他版本:

#define N_PEOPLE get_user_input()

pthread_t         th_ppl[N_PEOPLE]; 
pthread_mutex_t   m_ppl[N_PEOPLE];

int get_user_input() {
    int input;
    scanf("%d", &input);
    return (input);
}

int main(int argc, int **argv) {
    get_user_input();
    int m_id[N_PEOPLE];
    printf("%d", m_id);
}

其余的代码还不重要,但基本上我是在尝试在启动时捕获用户输入,这样我就可以创建一个线程数组和另一个互斥体,但是当我编译时出现错误第 3,4 行:“error: variably modified 'th_ppl' at file scope pthread_t th_ppl[N_PEOPLE]”。 - m_ppl.

相同

我有点明白为什么会出现此错误,因为我启动程序时未设置变量,所以我尝试了不同的方法,例如使用另一个全局变量来存储 int 或直接使用 return在全局中运行,例如:

phtread_t th_ppl[get_user_input()];

但我总是遇到同样的错误,而且我似乎还无法解决这个问题。所以我想知道我是否只是做错了,或者我是否应该完全改变我的策略。

您不能像发布的那样构造全局可变大小数组。你应该从用户那里读取人数,用calloc分配全局数组,并定义th_pplm_ppl作为指针。

这是一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int N_PEOPLE;

pthread_t *th_ppl; 
pthread_mutex_t *m_ppl;

int get_user_input() {
    int input;
    if (scanf("%d", &input) != 1)
        return 0;
    return input;
}

int main(int argc, int **argv) {
    N_PEOPLE = get_user_input();
    if (N_PEOPLE <= 0) {
        printf("invalid people number: %d\n", N_PEOPLE);
        exit(1);
    }
    th_ppl = calloc(sizeof(*th_ppl), N_PEOPLE);
    m_ppl = calloc(sizeof(*m_ppl), N_PEOPLE);
    if (th_ppl == NULL || m_ppl == NULL) {
        printf("cannot allocate memory for %d people\n", N_PEOPLE);
        exit(1);
    }
    printf("ready for %d people", N_PEOPLE);

    ...
}