I am very new to c programming. I have written the fallowing code
float value; //golbal variable
unsigned int data; //golbal variable
void Maxphase(void)
{
float MAX = 0.0;
unsigned int i,index;
for (i=0;i<=360;i++)
{
phaseset(i);
data = readvalue();
value = voltage(data);
if(value>MAX) //find max value
{
MAX = value; //max voltage
index = i;
}
}
printf("Max Voltage Value:%f\r\n", MAX);
printf("Related index Value:%d\r\n", index);
}
the above code working perfectly and printing maximum voltage and index. I want return both values “Max” and “index” from this function and I have to save Max value in one variable and index value in other variable like.
void runCom(void){
c=getchar();
switch(c){
case '1':
Maxphase();
Vin= (I want to store MAX value of that function)
p1= ( I want to store Index of that function)
break;
default:
break;
}
}
Actually I want call that function and it has to return two variables MAX and index value, thus I want to store those two values in different variables.
I know function can’t return two values.
I have searched, i found it is possible with a struct or make the function to handle the arguments with pointers. I tried with struct as shown below.
typedef struct {
float v;
unsigned int p;
}volphase;
I have declared this struct in header file. I am including this header file in all files where i am calling.
volphase Maxphase()
{
volphase vp;
float MAX = 0.0;
unsigned int i,index;
for (i=0;i<=360;i++)
{
phaseset(i);
data = readvalue();
value = voltage(data);
if(value>MAX) //find max value
{
MAX = value; //max voltage
index = i;
}
}
vp.v=MAX;
vp.p=index;
return vp;
}
This is written in “bvr.c” file.
But I am thinking how to call this “struct” in case’1′(main.c) and how to store vp.v in one variable and vp.p in another variable.
Please suggest me if any thing wrong in writing struct. or any other easiest way that will return two values.
please help me how to do this.
Returning a
structfrom the function is the least common of the two ways to return multiple values. Using pointers is more common:Here is how you call this function: