我是 C++ 的新手,我正在阅读 Alex Alllain 的这本名为Jumping into C++的电子书,它非常有帮助。
我最近完成了指针一章。本章末尾有一个练习题,要求你编写一个程序,比较堆栈上两个不同变量的内存地址,并按地址的数字顺序打印出变量的顺序。
到目前为止,我已经运行了该程序,但是如果我以正确的方式实施它,我并不满意,我希望获得有关我的解决方案的专家意见,以确定我是否朝着正确的方向前进。以下是我自己对问题的解决方案(评论和提示会有所帮助):
// 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;
}