You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中无法将线程函数的数组值传递至主函数问题求助

问题:pthread线程计算数组最值后无法将结果传递到主函数

你编写的代码中,无法传递最值结果的核心问题有两个:

  • *malloc(2)*分配的内存大小错误:int类型通常占4字节(具体取决于平台),要存储两个int值,需要分配*2 * sizeof(int)*字节的内存,否则会导致内存越界或数据存储不完整。
  • 分配内存后没有将计算得到的*min*和*max*值写入到这块内存中,直接返回了未初始化的指针,主函数读取的是无效数据。

以下是修正后的完整代码:

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

int array[1000];
int array_size;

void *min_max_thread(void *arg)
{
    int min = array[0];
    int max = array[0];
    for (int i = 1; i < array_size; i++)
    {
        if (min > array[i])
        {
            min = array[i];
        }

        if (max < array[i])
        {
            max = array[i];
        }
    }

    // 分配能存储两个int的内存
    int *min_max = malloc(2 * sizeof(int));
    if (min_max == NULL) {
        perror("malloc failed");
        pthread_exit(NULL); // 分配失败时退出线程
    }
    // 将计算结果存入内存
    min_max[0] = min;
    min_max[1] = max;
    return min_max;
}

int main(int argc, char *argv[])
{
    // 读取数组大小和元素
    printf("Enter the number of elements in the array: ");
    scanf("%d", &array_size);
    printf("Enter the elements of the array: ");
    for (int i = 0; i < array_size; i++)
    {
        scanf("%d", &array[i]);
    }
    pthread_t min_max_thread_id;

    // 创建线程
    pthread_create(&min_max_thread_id, NULL, min_max_thread, NULL);

    // 等待线程结束
    void *min_max_result;
    pthread_join(min_max_thread_id, &min_max_result);

    // 打印结果并释放内存
    if (min_max_result != NULL) {
        int *min_max = (int *)min_max_result;
        printf("Minimum: %d\n", min_max[0]);
        printf("Maximum: %d\n", min_max[1]);
        free(min_max); // 释放线程中malloc的内存,避免内存泄漏
    }

    return 0;
}

补充说明:

  • 增加了malloc失败的判断,避免空指针访问
  • 主函数中记得调用free(min_max)释放线程中分配的内存,防止内存泄漏
  • 确保<stdio.h>、<stdlib.h>、<pthread.h>头文件被正确包含,缺失头文件会导致编译报错

内容的提问来源于stack exchange,提问作者bradhrad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:50:17