我在C++新手,我讀這本電子書叫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;
}
我明白無論是目標,也不是問題;抱歉。 –
在C99或更高版本,您可以將兩個指針,以'uintptr_t'轉換(從'#包括'或'的#include ')和比較這些轉換後的值。它可能已經接近便攜式,但仍不能保證該標準。 –
畢竟已經在這個線程已經說了,可能是推薦的方式來做到這一點是使用[2]',而不是單獨的'x'和'y',然後將鼠標指針比較就定義好'INT XY。作爲一個方面說明,比較指向數組成員的指針是你在C中經常做的事情,而不是比較任意指向變量的指針。我甚至不能想象爲一個體面的例子:d –