Home > Net >  How to pass struct variable to function as argument or reference in C?
How to pass struct variable to function as argument or reference in C?

Time:08-07

I want to pass a struct variable as a function parameter (sorry for bad English.) Here is what I want to do:

#include <stdio.h>
#include <stdint.h>

typedef struct {
  int temp;
  int hum;
  int oxy;
} Data;

Data sens1;
Data sens2;
Data sens3;

sens1.temp = 5;
sens2.temp = 10;
sens3.temp = 15;


int ort(Data temp1 , Data temp2 , Data temp3)
{
  int ort = ((temp1   temp2   temp3) / 3);
  return ort;
}

int main(void)
{
  printf("%d", ort(sens1.temp, sens2.temp, sens3.temp));
  return 0;
}

How to add struct member called temp to function ort() as parameter?

CodePudding user response:

You cannot add structs, and that's what you are doing in temp1 temp2 temp3.

You probbaly want this:

int ort(Data sensor1 , Data sensor2, Data sensor2)
{
  int ort = ((sensor1.temp   sensor2.temp   sensor2.temp) / 3);
  return ort;
}
...
printf("%d" , ort(sens1, sens2, sens3);
...

or this:

int ort(int temp1, int temp2, int temp3)
{
  int ort = ((temp1   temp2   temp3) / 3);
  return ort;
}
...
printf("%d" , ort(sens1.temp, sens2.temp, sens3.temp);
...

CodePudding user response:

If you want to pass a reference to the struct rather than the whole struct, the typical method is something like:

#include <stdio.h>
#include <stdint.h>

struct data {
        int temp;
        int hum;
        int oxy;
};

struct data sens1 = { .temp = 5 };
struct data sens2 = { .temp = 10 };
struct data sens3 = { .temp = 15 };


float
ort(const struct data *d1, const struct data *d2, const struct data *d3)
{
        return (float)(d1->temp   d2->temp   d3->temp) / 3;
}

int
main(void)
{
        printf("%f\n", ort(&sens1, &sens2, &sens3));
        return 0;
}
  • Related