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

C语言函数接收双指针后传递给pthread线程函数的问题

Fixing Thread Parameter & Incomplete Type Issues in C

Hey there, let's work through your problems step by step—this kind of pointer/thread confusion is super common when you're new to C, so you're not alone!

First: Fixing the "dereferencing pointer to incomplete type" Error

This error happens because your process function doesn't have access to the full definition of struct mystruct. If you only declared struct mystruct; (a forward declaration) in the scope where process lives, the compiler knows it's a struct type but has no idea what's inside it—so it can't let you dereference pointers to it.

To fix this:

  • Put the complete struct mystruct definition in a header file (like mystruct.h) that you include in every source file that uses the struct (both where testing is defined and where process is defined).
  • Or, if everything is in one source file, make sure the struct definition comes before both testing and process functions.

Example of a complete struct definition:

// mystruct.h or top of your source file
typedef struct mystruct {
    // Add your struct members here (example fields)
    int thread_id;
    char message[50];
} mystruct;

Second: Fixing Thread Parameter Passing & Runtime Crashes

Let's break down your pointer confusion here:
Your testing function takes a mystruct **str parameter. That means:

  • str is a pointer to a pointer to a mystruct
  • *str is a pointer to an actual mystruct instance (the one you want your threads to use)

When you tried passing &(*str) to pthread_create, that's equivalent to passing str itself (since &(*str) just gives you back the original pointer str). So you were passing a mystruct ** to the thread, but then trying to treat it as a different type in process—that's why you got runtime crashes.

Correct Approach:

  1. Pass the right pointer to the thread: If you want all threads to access the same mystruct instance, pass (void*)*str (the actual pointer to the struct) to pthread_create.
  2. Convert back correctly in the thread function: Cast the void* argument back to mystruct * (not mystruct **).

Here's a corrected code example:

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

// Complete struct definition (visible to all functions)
typedef struct mystruct {
    int thread_id;
    char message[50];
} mystruct;

void *process(void *arg) {
    // Convert the void* back to mystruct* (matches what we passed)
    mystruct *value = (mystruct*)arg;
    
    // Now you can safely access struct members
    printf("Thread %d says: %s\n", value->thread_id, value->message);
    
    return NULL;
}

void testing(mystruct **str) {
    // First, make sure *str points to a valid mystruct instance (e.g., malloc'd)
    if (*str == NULL) {
        *str = malloc(sizeof(mystruct));
        if (*str == NULL) {
            perror("malloc failed");
            return;
        }
        // Initialize struct values
        (*str)->thread_id = 0;
        snprintf((*str)->message, sizeof((*str)->message), "Hello from shared struct");
    }

    pthread_t threads[5];
    for (int i = 0; i < 5; i++) {
        // Pass the pointer to the actual struct instance (*str)
        int ret = pthread_create(&threads[i], NULL, process, (void*)*str);
        if (ret != 0) {
            perror("Failed to create thread");
            // Cleanup if needed
            return;
        }
    }

    // Wait for all threads to finish (critical to avoid main exiting early)
    for (int i = 0; i < 5; i++) {
        pthread_join(threads[i], NULL);
    }

    // Don't forget to free the struct if you malloc'd it!
    free(*str);
    *str = NULL;
}

Why Your Previous Attempts Failed:

  • When you cast arg to mystruct ** in process, you were treating a mystruct * (or worse, a mystruct **) as a double pointer. Dereferencing that would try to read memory that's not a valid pointer, causing a crash.
  • The line struct mystruct **value = *(mystruct *)arg was a type mismatch: you were trying to assign a mystruct instance (from dereferencing a wrong cast) to a mystruct ** pointer, which the compiler rejected once it couldn't see the full struct definition.

Key Takeaways

  1. Always ensure struct definitions are visible to any function that needs to access their members.
  2. Match pointer types when passing to threads: What you pass as void* must match what you cast back to in the thread function.
  3. Don't forget to join threads: If your main function exits before threads finish, they'll be terminated abruptly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:24:09