简体   繁体   中英

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

I am having this function fun, where I am passing the nums structure as a parameter. The thing is that I need to convert this field into an integer inside the function. How can I do this without changing the way I am passing the structure in the function?

Here is what i am trying to do:

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);
    ...
}

Also, how can I do the casting for the head node? Can anyone please advice?

Since a struct numbers * is being passed to fun , you need to assign the parameter to a variable of this type. Then you can use the struct.

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

There's also a problem with how you populate the struct:

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

You're not allocating enough space for new_a . You only allocate 1 byte, but an int on most systems is 4 bytes. When you subsequently read and write from this memory location, you read/write past the end of the memory that was allocated. This invokes undefined behavior which in this case manifests as a crash..

You can fix this by allocating the proper amount of space:

new_a = malloc(sizeof(*new_a));

However, you don't need to use dynamic memory allocation for this field at all. Just declare new_a as int and write to it directly:

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

...

args->new_a = returnNum();

You also don't need to take the address of args . It's a pointer, so pass it to pthread_create directly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM