How to create an input method in C++ with pointers
First of all, you want to read int
s, not int*
s, so you need to dereference the pointers:
void inputTest(int* x, int* y) {
cin >> *x;
cin >> *y;
}
Then you need to pass valid pointers to the function - yours are null pointers and point nowhere at all.
The best way to do this is to first create two int
s and then acquire their locations with the "address-of" operator, &
.
int x = 0;
int y = 0;
cout << "Input: " << endl;
inputTest(&x, &y);
I'm new to pointers so I want to try it that way.. :)
Ok, then first lesson: Do not use pointers when you don't have to. Pointers can cause the most nasty bugs that you dont get without them.
Next: Pointers are just pointers. The can point to something. A int*
can point to an int
. Your pointers do not point to anything meaningful.
To store integer values you need int
s somewhere. Having pointers pointing somewhere is not sufficient. Once you have a int
, eg int x;
then &x
will give you a int*
namely the address of x
(&
is called the address-of operator, but dont get confused, &
can have a different meaning, see below). If you have the pointer, int* p = &x;
then you can dereference the pointer to get back x: *p = 5;
will set the value of x
to 5
. Using that you could write
void inputTest(int* x, int* y) {
std::cin >> *x;
std::cin >> *y;
}
int main() {
int x,y;
inputTest(&x,&y);
std::cout << x << " " << y;
}
BUT (would like to make it even more bold, because it really is a big "but"). There is an alternative and this is what you should use here. Pointers as parameters are useful when "not pointing anywhere" is an allowed parameter. For a fucntion that wants to read input from user and store that somewhere an invalid pointer is of little use. Better is to disallow such invalid input and use references:
void inputTest(int& x, int& y) {
std::cin >> x;
std::cin >> y;
}
int main() {
int x,y;
inputTest(x,y);
std::cout << x << " " << y;
}
I feel a bit bad for writing this answer, because when you are completely new to pointers, reading an answer here will not be enough to get a proper understanding. Get a book and read it.