下面的代码生成以下警告:‘factoryThread’ may be used uninitialized in this function [-Wmaybe-uninitialized]

    pthread_t factoryThreads[NUM_FACTORIES];
    int factoryNums[NUM_FACTORIES];
    for (int i = 0; i < NUM_FACTORIES; i++) {
        factoryNums[i] = i + 1;
        pthread_t factoryThread;
        factoryThreads[i] = factoryThread;
        pthread_create(&factoryThreads[i], NULL, createAndInsertCandy,
                &factoryNums[i]);
    }

代码似乎按预期工作,但我仍然很好奇是什么导致了警告,我可以做些什么来修复它。

最佳答案

通过使用具有自动存储持续时间的未初始化变量的值调用未定义的行为,该值是不确定的,并且它刚好起作用。
删除无意义的变量和赋值。

pthread_t factoryThreads[NUM_FACTORIES];
int factoryNums[NUM_FACTORIES];
for (int i = 0; i < NUM_FACTORIES; i++) {
    factoryNums[i] = i + 1;
    pthread_create(&factoryThreads[i], NULL, createAndInsertCandy,
            &factoryNums[i]);
}

09-28 08:47