Skip to content

How To Return A Struct From A Function In C++

An answer to this question on Stack Overflow.

Question

So I've thoroughly gone through the topics by searching this site but I couldn't find something which can help me.

I'm making a task for my friend and let me tell you that it's been a year or more since I've used C++.

So the problem I'm facing is with pointers and returning struct through pointer.

Here's the code below:

#include <stdio.h>
#include <conio.h>
#include <iostream.h>
	struct student
   {
   	int SUB[3];
   };
   struct AVGPCT
   {
   	float avg;
      float pct;
   };
AVGPCT* CALC(student *A)
{
   int x,y;
	AVGPCT D[5]={0.0,0.0,0.0,0.0,0.0};
   for(x=0;x<5;x++)
   {
   	for(y=0;y<3;y++)
      {
      	D[x].avg+=A[x].SUB[y];
         D[x].pct+=A[x].SUB[y];
      }
   }
   for(x=0;x<5;x++)
   {
   	D[x].avg/=2;
      D[x].pct/=300;
   }
   return (D);
}
void main(void)
{
   int i,j;
   student S[5];
   AVGPCT *V;
   for(i=0;i<5;i++)
   {
   	for(j=0;j<3;j++)
      {
      	cout << "Enter Marks Of Subject[" << (j+1) << "] Of Student [" << (i+1) <<"] [Max=100]:";
      	cin >> S[i].SUB[j];
      }
   }
   V = CALC(S);
   cout << "Average Number Of Student [1]: " << V->avg;
   cout << (*V).pct;
   getch();
}

Now the problem is, it is giving me a hard time to retrieve correct values from the location.

I'm trying to increment the pointer with V++. The funny thing is it is printing the values correctly if I use:

cout << V->avg;
cout << V->pct;
V++;
cout << V->avg;
cout << V->pct;

And so on. But if I use loop or write even a single line or use endl or \n, the values jumble up and gibberish values appear.

So what could be going wrong here?

It is important that I use struct and also please guide according to the code.

Answer

Looks like this line

AVGPCT D[5]={0.0,0.0,0.0,0.0,0.0};

declares the array D locally to the function CALC()

You pass a pointer to that array back to the main function, but the array is marked as free game for overwriting when the function ends. The more stuff you do in the program, the more chance there is of this location in memory being overwritten, though it's hard to say when that will happen. Hence, sometimes you get away with it, other times you don't.

At the risk of giving you advice, it's probably better to declare D somewhere in main and pass a pointer to it into the function or use a new or malloc inside the function and pass the resultant pointer back.