Hi there,

I have searched for an answer to this problem but cannot find one even though there is probably a very simple solution. I would like to pass an int to a function in pthread_create. I can do that easily. The troublesome part is when I have to cast it within the function from a void pointer to an int. I get a segmentation fault on the computers at Varsity when I do this:

void *threadfunc(void *arg) {
    int number = (int*) arg;
}

int main(int argc, char *argv[]) {
    pthread_t thread[3];
    for (int i = 0; i < 3; i++) {
         pthread_create(&thread[i], NULL, threadfunc, (void*)i);
    }
    for (int i = 0; i < 3; i++) {
         pthread_join(thread[i], NULL);
    }
    return 0;
}

Please help.

Thanks :)

Try casting the address of i instead of the value. For instance (void *) &i casts the address of i, (void *) i casts the value. In the latter case you would be trying to read the value at location 0x0, 0x1 and 0x2. In addition, when you assign in your thread function, you need to assign to an int pointer ( int * number = (int *) arg; );

Thanks. Implementing both of your suggestions worked. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.