Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

// the logic works but I cannot calle the data back from the latter function //p

ID: 3718729 • Letter: #

Question

// the logic works but I cannot calle the data back from the latter function

//please find a solution to use that pointer to retrieve the infomation to the main function. Thank you

#include <iostream>
using namespace std;

struct Date
{
   int month;
   int day;
   int year;
};
void latter(Date,Date, Date);
int main()
{

Date d1;
Date d2;
Date *p;

cout << "please enter the first date month, day, year: "<<endl;
cin >> d1.month >> d1.day>> d1.year;

cout << "please enter the second date month, day, year: " << endl;
cin >> d2.month >> d2.day >> d2.year;

latter(d1, d2, p);

cout << endl;
cout <<(*p).month<< "/" <<(*p).day<< "/" <<(*p).year<<endl;
   system("pause");
    return 0;
}

void latter(Date d1, Date d2, Date *p)
{
   if (d1.year > d2.year)
       p = &d1;
   if (d1.year < d2.year)
       p = &d2;
   if (d1.year == d2.year)
   {
       if (d1.month > d2.month)
           p = &d1;
       if (d1.month < d2.month)
           p = &d2;

       if (d1.month == d2.month)
       {
           if (d1.day > d2.day)
               p = &d1;
           if (d1.day < d2.day)
               p = &d2;
           if (d1.day == d2.day)
               p = &d1;
       }
   }
}

Explanation / Answer

#include <iostream>
using namespace std;

struct Date
{
int month;
int day;
int year;
};
void latter(Date,Date, Date*); // you missed the * for passing the third parameter as a pointer.
int main()
{

Date d1;
Date d2;
Date *p = new Date(); // allocte memory to the pointer. Then only the contents at that memory location can be changed

cout << "please enter the first date month, day, year: "<<endl;
cin >> d1.month >> d1.day>> d1.year;

cout << "please enter the second date month, day, year: " << endl;
cin >> d2.month >> d2.day >> d2.year;

latter(d1, d2, p);

cout << endl;
cout <<(*p).month<< "/" <<(*p).day<< "/" <<(*p).year<<endl;
system("pause");
return 0;
}

void latter(Date d1, Date d2, Date *p)
{
if (d1.year > d2.year)
*p = d1; // dereference the memory location to edit its contents
if (d1.year < d2.year)
*p = d2;
if (d1.year == d2.year)
{
if (d1.month > d2.month)
*p = d1;
if (d1.month < d2.month)
*p = d2;

if (d1.month == d2.month)
{
if (d1.day > d2.day)
*p = d1;
if (d1.day < d2.day)
*p = d2;
if (d1.day == d2.day)
*p = d1;
}
}
}