1

私は 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;
}
4

3 に答える 3

3

これは「正しい」ですが、明確に定義された動作ではありません。同じ配列内の要素のアドレス、または構造体の同じインスタンスのメンバーのみを比較できます。C99 (6.5.8) から: *

2 つのポインターを比較すると、結果は、指しているオブジェクトのアドレス空間内の相対位置によって異なります。オブジェクト型または不完全型への 2 つのポインターが両方とも同じオブジェクトを指している場合、または両方が同じ配列オブジェクトの最後の要素の 1 つ後ろを指している場合、それらは等しく比較されます。指しているオブジェクトが同じ集約オブジェクトのメンバーである場合、後で宣言された構造体メンバーへのポインターは、構造体で以前に宣言されたメンバーへのポインターよりも大きく、添字値が大きい配列要素へのポインターは、同じ配列の要素へのポインターよりも大きくなります。より低い添字値で。同じ共用体オブジェクトのメンバーへのすべてのポインターは等しいと比較されます。式 P が配列オブジェクトの要素を指し、式 Q が同じ配列オブジェクトの最後の要素を指す場合、それ以外の場合、動作は未定義です。

(私のものを強調)

したがって、これはおそらく上司が探していたものであり、おそらく「機能する」でしょうが、言語標準に関する限り、まだ有効ではありません.


* C++ 標準のセクション [expr.rel] は似たようなことを言っていますが、クラス メンバーの警告などにより、より冗長になっています。また、それ以外は「未定義」ではなく「未指定」であると述べています。

于 2013-01-06T19:10:38.543 に答える
0

アカデミックなタスクとして、これはまったく問題ありません..あなたは本の「要件」を満たしています

于 2013-01-06T19:17:00.450 に答える
0

他の人が指摘したように、同じ集約内のオブジェクトを指していないポインターの比較は未定義の動作です。ただし、ポインター型の完全な順序付けには std::less を使用できます ( http://en.cppreference.com/w/cpp/utility/functional/lessを参照) 。

于 2013-01-07T16:08:06.563 に答える