C 初始化类型定义的结构指针

C Initializing type defined structure pointers

嗯,我在初始化全局定义的类型结构时遇到问题。

定义的类型是:

typedef struct {
    pthread_t pthread;
    int status;
    int id;
    time_t entrada;
} Cliente;

我使用的全局声明是这样的:

Cliente *cola=malloc(sizeof(Cliente));

但编译器说它必须由一个 CONSTANT

定义

目标是拥有一个名为 cola 的 Cliente 类型的动态数组。 如果我没有很好地初始化它们,我会在执行 0.00 秒时遇到分段错误。 将其作为全局变量的原因是因为它是线程之间共享的资源,我知道这不是最佳实践,但我必须这样做。

我不知道我会有多少 Cliente(可以是默认数字或一个 argv 随机输入)所以这就是我实现和结构指针的原因。

提前致谢:)

在全局范围内定义它并在首次使用前为其分配内存。例如:

Cliente* cola;

int main(int argc, char** argv)
{
    if (argc < 2) {
        perror("First arg indicates thread numbers and is required");
    }

    int thread_count = atoi(argv[1]);
    cola = malloc(sizeof(*cola) * thread_count);
    ...
    // Extend cola size without losing previous data
    cola = realloc(cola, sizeof(*cola) * (thread_count + x));
}