Linux C線程編程與二級指針做函數參數

二級指針做函數入參,則函數內部可以修改指針,即修改指針的指向(指針本身的值),本文結合簡單的線程編程進行實際說明

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

typedef struct tagExSt {
    int a;
    int b;
    int c;
} ExSt;

void ThreadFunc(void *args)
{
    ExSt *pstExst = (ExSt *)malloc(sizeof(struct tagExSt));
    printf("This is thread!\n");
    pstExst->a = 1;
    pstExst->b = 2;
    pstExst->c = 3;
    printf("a = %d, b = %d, c = %d\n", pstExst->a, pstExst->b, pstExst->c);
    pthread_exit(pstExst); // 將指針進行返回,若指針是局部變量,則函數退出
                           // 會被釋放,再使用會段錯誤或值不對
}
int main()
{
    pthread_t pthid;
    ExSt *pstExst;
    pthread_create(&pthid, NULL, ThreadFunc, NULL);
    printf("This is main process!\n");
    pthread_join(pthid, &pstExst); // 傳入指針的地址,則函數中可以修改指針的值
    printf("a = %d, b = %d, c = %d\n", (ExSt *)pstExst->a, (ExSt *)pstExst->b, (ExSt *)pstExst->c);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章