这是根据两个变量的内存地址进行数值排序的有效方法吗?

Is this a valid approach for numerical order of two variables by their memory addresses?

本文关键字:排序 有效 方法 地址 内存 变量 两个      更新时间:2023-10-16

我是一个c++新手,我正在阅读Alex Allain写的这本名为《跳入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 (6.5.8):*

比较两个指针时,结果取决于相对指针所指向对象的地址空间中的位置。如果两个指向对象类型或不完整类型的指针都指向同一个对象,或者都指向同一个数组对象的最后一个元素的后面比较平等的。如果所指向的对象是同一对象的成员聚合对象,指向结构成员的指针稍后声明比较大于指向结构中前面声明的成员的指针,指向下标值较大的数组元素的指针比较大于指向具有lower的同一数组元素的指针下标的价值观。指向同一联合对象成员的所有指针比较平等的。如果表达式P指向数组的一个元素对象,表达式Q指向该对象的最后一个元素数组对象,指针表达式Q+1比较p In

(empahsis矿)

所以这可能是你的导师正在寻找的,它可能会"工作",但就语言标准而言,它仍然是无效的。


* Sectionc++标准的rel]说了类似的东西,但由于类成员的警告等等,它更冗长。它还指出,任何其他内容都是"未指定的",而不是"未定义的"。

作为学术任务这完全没问题。你满足了书中的"要求"

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