Zoubro
Zoubro

Reputation: 39

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

I'm writing a simulation program where the user is suppose to enter an int to define the number of people involved in the simulation, and I need to use the same input to set a pair of global variables. I tried the following and other version of it:

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

The rest of the code isn't important yet, but basically I'm trying to catch the user input at launch so I can create an array of thread and an other of mutexes, but when I compile I get errors line 3,4: "error: variably modified 'th_ppl' at file scope pthread_t th_ppl[N_PEOPLE]". - same for the m_ppl.

I kinda get why I have this error, because I launch the program with my variables unset yet so I tried differents approach, like using another global to store the int or to directly using the return of the function in the global, like:

phtread_t th_ppl[get_user_input()];

but I always get the same error, and I dont seem to be able to work around this problem yet. So I'd like to know if I'm just doing it wrong or if I should just completely change my strategy here.

Upvotes: 2

Views: 437

Answers (1)

chqrlie
chqrlie

Reputation: 144695

You cannot construct global variable size arrays as posted. You should read the number of people from the user, allocate the global arrays with calloc, and define th_ppl and m_ppl as pointers.

Here is an example:

#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);

    ...
}

Upvotes: 2

Related Questions