簡體   English   中英

如何將函數中的一個參數轉換為void指針參數到整數

[英]How to cast one parameter in function as void pointer parameter to an integer

我在使用此函數很有趣,在這里我將nums結構作為參數傳遞。 問題是我需要將此字段轉換為函數內部的整數。 如何在不更改在函數中傳遞結構的方式下執行此操作?

這是我想做的事情:

struct node{
    char *str;
    struct node *next;
};

struct numbers{
    struct node *head;
    int *new_a;
};

void *fun(void *args);

int main(int argc , char *argv[])
{
        int *new_a, num_a;
        struct node *head=NULL;

        struct numbers *args = (struct numbers *)malloc(sizeof(struct numbers));

        num_a = returnNum();

        pthread_t pthread;
        new_a = malloc(1);
        *new_a = num_a;
        args->new_a=new_a;

        if( pthread_create( &pthread , NULL , (void *) &fun , (void *) &args) < 0)
        {
            perror("could not create thread");
            return 1;
        }

}

void *fun(void *args){

    //void *num_a = (int *) args->new_a;
    //int num_a = *(int*)(args->new_a);
    struct numbers *temp_str = (struct numbers *) (*args);
    int num_a = (int) *(args->new_a);
    ...
}

另外,如何對頭節點進行轉換? 任何人都可以請教嗎?

由於將struct numbers *傳遞給fun ,因此您需要將參數分配給這種類型的變量。 然后,您可以使用該結構。

void *fun(void *arg){
    struct numbers *temp_str = arg;   // no need to cast from void *
    int num_a =  temp_str->new_a;
    ...
}

如何填充結構也存在問題:

    int *new_a, num_a;
    ...
    new_a = malloc(1);
    *new_a = num_a;
    args->new_a=new_a;

您沒有為new_a分配足夠的空間。 您只分配1個字節,但是在大多數系統上,一個int是4個字節。 當您隨后從該內存位置進行讀寫時,您將在已分配內存的末尾進行讀寫。 這將導致未定義的行為 ,在這種情況下將顯示為崩潰。

您可以通過分配適當的空間來解決此問題:

new_a = malloc(sizeof(*new_a));

但是,您根本不需要為此字段使用動態內存分配。 只需將new_a聲明為int並直接寫入即可:

struct numbers{
    struct node *head;
    int new_a;
};

...

args->new_a = returnNum();

您也不需要使用args的地址。 它是一個指針,因此將其直接傳遞給pthread_create

if( pthread_create( &pthread , NULL , fun , args) < 0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM