0

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?

3
  • First of all: indent your code. Commented Aug 6, 2022 at 9:28
  • You're adding Data structures in temp1 + temp2 + temp3, that doesn't make sense (and won't compile). Please explain what the ort function is supposed to do. Commented Aug 6, 2022 at 9:30
  • i create struct which names Data, then i create 3 objects , Data sens1 , Data sens2 and Data sens3. The ort function has to sum sens1.temp + sens2.temp + sens3.temp and divide them to 3 and return the value Commented Aug 6, 2022 at 10:38

2 Answers 2

2

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);
...
Sign up to request clarification or add additional context in comments.

2 Comments

thanx for your answer, and could you please tell what can be done for reduce the memory used by this function?
This piec of code does not use mich memory. There is not much you can do. Why do you think you need "reduce memory" here?
1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.