'I’m trying to sum the return value of 2 threads together but it return -1 saying error

I’m trying to make a program which sums the numbers in an array, the first half of the array by the first thread and the second half by the second thread and then printing out to the terminal the sum of both.

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

int vettore[10] = {1,2,3,4,5,6,7,8,9};

void *p1 (void *arg){
    int *primoritorno = (int *)malloc(sizeof(int));
    for(int i=0; i<=4 ; i++){
        *primoritorno+=vettore[i];
        }
    printf("Il valore della prima metà e' %d \n", *primoritorno);
    return primoritorno;

}

void *p2 (void *arg){
    int *secondoritorno = (int *)malloc(sizeof(int));
    for(int i=0; i<=4 ; i++){
        *secondoritorno+=vettore[i+5];
        }
    printf("Il valore della seconda metà e' %d \n", *secondoritorno);
    return secondoritorno;

}

int main (int argc, char **argv){
    int risultato = 0;
    void *primameta;
    void *secondameta;

    pthread_t primo;
    pthread_t secondo;

    pthread_create (&primo, NULL, p1, NULL);
    pthread_join (primo, &primameta);
    
    pthread_create (&secondo, NULL, p2, NULL);
    pthread_join (secondo, &secondameta);

    //risultato=primameta+secondameta;
    printf("Il risultato e' %d \n", risultato);
    return 0;
}


Solution 1:[1]

Your code is not summing the results, "risultato=primameta+secondameta;" is commented out. Regarding your question "Do I have to cast the pointers to int* in the function or in the main? Because I just tried and it’s saying that primoritorno and secondoritorno aren’t declared in this scope" I would declare primameta and secondameta as int pointers; So you could just dereference it when summing the results. As consequence, you would have to cast it to double void pointer when joining the thread. Like this:

int *primameta;
int *secondameta;

pthread_t primo;
pthread_t secondo;

pthread_create (&primo, NULL, p1, NULL);
pthread_join (primo, (void**)&primameta);

pthread_create (&secondo, NULL, p2, NULL);
pthread_join (secondo, (void**)&secondameta);

risultato = *primameta + *secondameta;
printf("Il risultato e' %d \n", risultato);

Also, please, note that vettore is declared with length 10, but only 9 integers were assigned to it and in the for loop of p2, the iteration goes until i<=4, for i = 4, it is trying to add vettore at its 9th position which is not initialized. You could declare vettore[9] = {...} and loop until i<4;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nicolasbk