繁体   English   中英

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

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

我是C ++的新手,我正在读这本名为Jumping into C ++的电子书Alex Allain非常有帮助。

我最近完成了指针章节。 本章末尾有一个练习题,它要求你编写一个程序来比较堆栈上两个不同变量的内存地址,并按地址的数字顺序打印出变量的顺序。

到目前为止,我已经开始运行该程序,但如果我以正确的方式实现它,我不满意,我想要一个关于我的解决方案的专家意见,以确定我是否正朝着正确的方向前进。 以下是我自己的问题解决方案(评论和提示将有所帮助):

// 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): *

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

(empahsis mine)

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


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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM