Sai Shankar
Sai Shankar

Reputation: 61

Return value void * in a function

I was given a function whose return value is void *. I need to return two values from that function.

void * studentsCount(int *Arr, int len, int score, int *lessCount, int *moreCount) {
    if (Arr == NULL || len <= 0)
        return NULL;
    for (int i = 0; i < len; i++){
        if (Arr[i] < score)
            *lessCount++;
        else if (Arr[i] > score)
            *moreCount++;
    }
    return lessCount;  // <-- I need to return lesscount and morecount..!
}

How can I return both values using void pointer?

Upvotes: 2

Views: 1439

Answers (3)

RodrigoBurgosMella
RodrigoBurgosMella

Reputation: 101

You must pass the variables by reference when calling the function

studentsCount(<var Arr>,<var len>,<var score>,&<var lessCount>,&<var moreCount>);

In addition, you can not use the increment or decrement operators in a variable used by reference, because of they a pointer. Attached an example function code, with call by reference for variables, i hope, this help you

void ejemplo(int *valor1, int *valor2){
    int valor1_val=*valor1;
    int valor2_val=*valor2;
    printf("\nValues in Function\n");
    printf("Before Asignation\n");
    printf("Numero1 [%d]\nNumero2 [%d]\n",valor1_val,valor2_val);
    valor1_val++;
    valor2_val--;
    printf("After Asignation\n");
    printf("Numero1 [%d]\nNumero2 [%d]\n\n",valor1_val,valor2_val);
    *valor1=valor1_val;
    *valor2=valor2_val;
    printf("Return to Main Code\n\n");
}

int main(int argc, char **argv){
   int numero1=100;
   int numero2=100;
   printf("In Main, before function call\n");
    printf("Numero1 [%d]\nNumero2 [%d]\n",numero1,numero2);
    ejemplo(&numero1,&numero2);
    printf("After function call\n");
    printf("Numero1 [%d]\nNumero2 [%d]\n",numero1,numero2);
    exit(0);
}

Upvotes: 0

P0W
P0W

Reputation: 47854

You don't have to return moreCount and lessCount, you just have to update their values inside the function.

As per return type void * is concerned, I would assume it signifies if the passed array is a "valid" array, if it is you may choose to return a non null value ( depends on how the studentsCount function is invoked ).

The caller should also make sure moreCount and lessCount points to a valid memory location, initialized to proper values

Upvotes: 2

James Maa
James Maa

Reputation: 1794

No, you need to pass at least one of them by parameter.

Upvotes: 0

Related Questions