I am writing my first C++ program to test out pointers and classes.
I don't understand what I am doing wrong here, but it doesn't return the correct answer? I am trying to send a pointer to the HighestAge function, so it can cycle through the 3 array elements to work out which one is the biggest.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
usingnamespace std;
class Person {
public:
string Name;
int Age;
};
int HighestAge(int *p) {
int HighAge = 0;
int ThisAge = 0;
for (int y = 0; y < 3; y ++) {
ThisAge = *(p+y);
// cout << "\n START " << thisone;
if (ThisAge > HighAge)
{
HighAge = ThisAge;
}
// cout << "\n END " << thisone << "\n\n";
}
return HighAge;
}
int main()
{
Person People[3];
int *p;
int y;
for (int x=0; x < 3; x++) {
cout << "\n \n Enter person number " << x << "'s age: ";
cin >> People[x].Age;
}
p = &People[0].Age;
cout << "p is " << p;
cout << "Highest age is " << HighestAge(p);
cout << "\n \n Enter anything to exit...";
cin >> y;
return 0;
}
You are passing your function an int pointer, and acting as if there is an array of three int values. There is no such array. You made an array of Person objects.
Pass your function a pointer to the first Person object in the array and go from there.
People[0] is the first Person object in the array of three Person objects you made.
People[0].Age is the Age member variable inside that first Person object.
&People[0].Age, also known as &(People[0].Age) is a pointer to that Age member variable inside the first Person object, which is an int, so this is a pointer to an int.
So if you go from that memory location, and you go forwards the amount of memory that a single int takes up (which is what adding the value one to an int pointer does), what do you find? What will be there? Given that there are not three ints in a row in memory, it will not be another int.
Thank you - so would you say this is not the correct way to go about it, as presumably the string is stored in that memory area too? (and can be variable length)?