Search code examples
cpointersgccstructfunction-definition

Passing structs to a function using the pointer operator in C


In this code:

the struct I have has 2 members and with it, 3 variables are defined.

the values of two of them are assigned by me and the third one should come from a function.

the code:

#include <stdio.h>

#include <stddef.h>
typedef unsigned short      int u16;        /*2 byte unsigned int*/
typedef unsigned char            u8;        /*1 byte unsigned char*/



typedef struct 
{
    u8 id;
    u8 salary;
} Emp;
void Math (Emp *Ptr1, Emp *Ptr2, Emp *resPtr);



void main ()
{
    Emp Ahmed = {100, 100};
    Emp Ali = {200, 200};
    
    Emp Result = {0,0};
    
    Math (&Ahmed, &Ali, &Result);
    printf("%d\n%d\n", Result.id, Result.salary);   
    
}


void Math (Emp *Ptr1, Emp *Ptr2, Emp *resPtr)
{
    resPtr -> id = Ptr1 -> id + Ptr2 -> id;
    resPtr -> salary = Ptr1 -> salary + Ptr2 -> salary;
}

the result is :

44
44

I'm using gcc toolchain, where exactly am I going wrong?


Solution

  • An unsigned char can only hold values as large as 255. Assigning a larger value will cause it to be effectively truncated to the lowest 8 bits.

    Change the datatype of the members to unsigned short. Then they'll be able to hold the result.