I was working on a coding exercise, where the user enters two integers, and the code displays the integers via pointers. When I declared the pointers and then pointed them to values a and b later on in the code, the code didn't compile. However, telling the pointers where to point right off the bat (when they are declared) works. I was wondering why the first way did not work.
Code That Did Not Work
// variables
int a;
int b;
// Ask for int a
cout << "Enter integer a : ";
cin >> a;
// Ask for int b
cout << "Enter integer b : ";
cin >> b;
// Pointing pointers to a and b;
*ptrA = &a;
*ptrB = &b;
// Print values a and b
cout << "a: " << *ptrA << endl;
cout << "b: " << *ptrB << endl;
Code That Worked
// variables
int a;
int b;
int *ptrA = &a;
int *ptrB = &b;
// Ask for int a
cout << "Enter integer a : ";
cin >> a;
// Ask for int b
cout << "Enter integer b : ";
cin >> b;
// Print values a and b
cout << "a: " << *ptrA << endl;
cout << "b: " << *ptrB << endl;