私は C++ の初心者で、非常に役立つ Alex Alllain のJumping into C++という電子ブックを読んでいます。
最近、ポインターの章を終了しました。章の最後に演習問題があり、スタック上の 2 つの異なる変数のメモリ アドレスを比較し、アドレスの番号順に変数の順序を出力するプログラムを作成するよう求められます。
これまでのところ、プログラムを実行できましたが、正しい方法で実装したかどうかに満足できず、正しい方向に向かっているかどうかを判断するために、ソリューションに関する専門家の意見が必要です。以下は、問題に対する私自身の解決策です(コメントとヒントが役立ちます):
// pointersEx05.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
int x,y; // two integer type variables
int *firstVal, *secondVal; // two pointers will point out to an int type variable
std::cout << "enter first value: ";
std::cin >> x; // prompt user for the first value
std::cout << std::endl << "enter second value: ";
std::cin >> y; // prompt user for the second value
std::cout << std::endl;
firstVal = &x; // point to the memory address of x
secondVal = &y; // point to the memory address of y
std::cout << firstVal << " = " << *firstVal; // print out the memory address of the first value and also the value in that address by dereferencing it
std::cout << "\n" << secondVal << " = " << *secondVal; // print out the memory address of the second value and also the value in that address by dereferencing it
std::cout << std::endl;
if(firstVal > secondVal){ // check if the memory address of the first value is greater than the memory address of the second value
std::cout << *secondVal << ", "; // if true print out second value first then the first value
std::cout << *firstVal;
}else if(secondVal > firstVal){ // check if the memory address of the second value is greater than the memory address of the first value
std::cout << *firstVal << ", "; // if true print out first value first then the second value
std::cout << *secondVal << ", ";
}
return 0;
}