I'm trying to pick my C skills again. I want to sum a sequence in different threads, each thread would return a pointer of the sum of a part of the sequence. However, when I tried to convert the void*
type value local_sum
to int
, problem occurred.
I tried to convert with sum += *(int*)local_sum;
, a segment error occurred and I got Process finished with exit code 11
.
I found that if I use sum += (int)local_sum;
, it would be okay. But I couldn't convince myself: shouldn't local_sum
be a void *
? Why it can be converted to int
with (int)local_sum
?
I'm so grateful it you could answer the problem.
The part that sum each process's return value is here:
int sum = 0;
for (int i = 0; i < NUM_THREADS; i ++) {
void * local_sum;
pthread_join(count_threads[i], (&local_sum));
sum += (int)local_sum;
}
The function of a thread is here:
void * count_thr(void *arg) {
int terminal = ARRAY_SIZE / NUM_THREADS;
int sum = 0;
for (int i = 0; i < terminal; i ++) {
sum += *((int*)arg + i);
}
return (void*)sum;
}