Search code examples
cfunctionstructreturn

passing a struct to a function doesnt work


In the below code I have create a function apart from main to divided the int inside a struct into half.

After that, I want to print out the new value. However, the print out value is still the old one.

I believe my fundamental knowledge of struct and pointers are not good enough.

Can anyone help me with this? Thanks a lot!!!

typedef struct{
    int age;
    int wage;
}person;


void divide(person A)
{
    person half;
    half.age = A.age / 2;
    half.wage = A.wage / 2;
    
    A = half;
}

int main(void)
{
    person A;
    A.age = 30;
    A.wage = 35000;
    
    divide(A);
    
    printf("%i\n", A.age);

}

Solution

  • The function divide is modifying a copy of that structure since structures are pass by value. You will need to pass the pointer to the structure, so the function can modify the original.

    void divide(person* A)
    {
        person half;
    
        half.age  = A->age  / 2;
        half.wage = A->wage / 2;
        
        *A = half;
    }
    

    Called divide with address of original structure

    divide(&A);