array reference or pointers for get set function

main.cpp
1
2
3
4
5
6
7
8
Person per[100];
int favNumber[10];

for (int i = 0; i < 3; i++) {
cout << "enter favorite number" << endl;
cin >> favNumber[i];
per[0].setFavNum(favNumber[i]);
}


Object Person.h
1
2
3
4
5
6
7
8
9
10
11
class Person {

private:
name
favNum[3];

public:
Customer(name,favNum[3]);
int getFavNum(int);
void setFavNum(int);
};


Person.cpp
1
2
3
4
5
6
7
int Person::getFavNum(int num) {
return interest[num];
}

void Person::setFavNum(int _favNum) {
favNum = _favNum;
}


my setFavNum is wrong..can anyone teach me how do i set fav num by reference or pointers. i am new to reference and pointers. since i have an array of 3 fav num, i have no item to set it property to my person object. i am only able to set 1 value into it.
Part of loop from lines 3 to 8 should be done inside void Person::setFavNum(). The function should accept not a single int, but an array of ints. Of course, you cannot define a function like this
void Person::setFavNum(int _favIntArray[]) // WRONG!
But you can make it accept pointers pointing to first element of integer array, and pointers can be used similarly to arrays:
1
2
3
4
5
6
7
8
9
void Person::setFavNum(int * favNumPointer )
{
	for (int i = 0; i < 3; i++)
	{
		this.favNum[i] = *(favNumPointer + i); 
		// the syntax requires the * to access values stored in pointed memory cells.
		// + i to refer to each subsequent element of original array
	}
} 


Now in main.cpp:
1
2
3
4
5
6
7
8
9
Person per[100];
int favNumber[10];

for (int i = 0; i < 3; i++) {
	cout << "enter favorite number" << endl;
	cin >> favNumber[i];
}
per[0].setFavNum(favNumber) // Pasing name of original array, not any of it's cells
Last edited on
I thought the form

void Person::setFavNum(int _favIntArray[])

was equally valid?

After all

int main(int argc, char* argv[])

is a very common form of the main function.

Andy

PS see example in section "Arrays as parameters" on this page

Arrays
http://www.cplusplus.com/doc/tutorial/arrays/
Topic archived. No new replies allowed.