这是两个变量按其内存地址排序的有效方法吗?

时间:2013-01-06 19:08:38

标签: c++ pointers

我是C ++的新手,我正在阅读Alex Allain撰写的这本名为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;
}

3 个答案:

答案 0 :(得分:3)

这是“正确的”,但它没有明确定义的行为。您只能比较同一数组中元素的地址,或结构的同一实例的成员。来自C99(6.5.8): *

  

当比较两个指针时,结果取决于相对值   指向的对象的地址空间中的位置。如果两个   指向对象或不完整类型的指针都指向同一个对象,   或者两者都指向同一个数组对象的最后一个元素,它们   比较平等。如果指向的对象是同一个成员   聚合对象,指向稍后声明的结构成员的指针   大于指向结构中先前声明的成员的指针,   和指向具有较大下标值的数组元素的指针进行比较   大于指向同一数组元素的指针   下标值。指向同一个union对象的成员的所有指针   比较平等。如果表达式P指向数组的元素   对象和表达式Q指向同一个的最后一个元素   数组对象,指针表达式Q + 1比大于P. In   在所有其他情况下,行为未定义。

(empahsis mine)

所以这可能是你的主管正在寻找的东西,它可能会“起作用”,但就语言标准而言,它仍然无效。

<小时/> * C ++标准的[expr.rel]部分说了类似的内容,但由于课堂成员的警告等等,它更加冗长。并且它还声明其他任何内容都是“未指定”而不是“未定义”。

答案 1 :(得分:0)

作为一项学术任务这完全没问题......你完成了本书的“要求”

答案 2 :(得分:0)

正如其他人所说,指向不指向同一聚合中的对象的指针的比较是未定义的行为。但是你可以使用std :: less来获得指针类型的总排序(参见:http://en.cppreference.com/w/cpp/utility/functional/less