Arrays and Functions

Hi all,

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.

Your help is most welcome...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  // ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"

using namespace 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.

Thanks,

I thought I was doing that here:

 
p = &People[0].Age;


and then

ThisAge = *(p+y);

Would cycle through the values... but it doesn't seem to work.



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)?
Topic archived. No new replies allowed.