如果堆栈在数字较低的地址处增长,为什么指针比较会逆转呢? [英] If the stack grows at numerically lower address why does pointer comparison reverses this?

查看:101
本文介绍了如果堆栈在数字较低的地址处增长,为什么指针比较会逆转呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于堆栈向下增长,即朝向数值较小的内存地址,为什么&i < &j为true.如果我错了,请指正我,但是我想这是C创建者(由C ++维护)的设计决策.但是我不知道为什么.

Since the stack grows downwards, ie towards numerically smaller memory addresses why does &i < &j is true. Correct me if I'm wrong, but I'd imagine this was a design decision of C creators (that C++ maintains). But I wonder why though.

奇怪的是,堆分配的对象pin在数值上比堆栈变量位于更高的内存地址,这也与以下事实相矛盾:堆位于数值上比堆栈小的内存地址(并向上增加).

It is also strange that a heap-allocated object pin lies at numerically higher memory address than a stack variable and this also contradicts the fact that the heap lies at numerically smaller memory addresses than the stack (and increases upwards).

#include <iostream>

int main()
{
    int i = 5;                  // stack allocated
    int j = 2;                  // stack allocated
    int *pi = &i;               // stack allocated
    int *pj = &j;               // stack allocated

    std::cout << std::boolalpha << '\n';
    std::cout << (&i < &j) && (pi < pj) << '\n';            // true
    struct S
    {
        int in;
    };
    S *pin                      // stack allocated
        = new S{10};            // heap allocated
    std::cout << '\n' << (&(pin->in) > &i) << '\n';         // true
    std::cout << ((void*)pin > (void*)pi) << '\n';          // true
}

我到目前为止是对的,如果是这样,为什么C设计人员会扭转这种情况,即数字上较小的内存地址会显得更高(至少当您比较指针或通过操作符&的地址时).只是为了使事情正常"吗?

Am I right so far and if so why C designers reversed this situation that numerically smaller memory addresses appear higher (at least when you compare the pointers or through the addressof operator &). Was this done just 'to make things work'?

推荐答案

如果我错了,请纠正我,但我想这是C创作者的设计决定

Correct me if I'm wrong, but I'd imagine this was a design decision of C creators

它不是C语言或C ++设计的一部分.实际上,这些标准不存在诸如堆"或堆栈"内存之类的东西.

It is not part of the design of the C language, nor C++. In fact, there is no such thing as "heap" or "stack" memory recognised by these standards.

这是一个实现细节.每种语言的每种实现方式可能都不同.

It is an implementation detail. Each implementation of each language may do this differently.

指向不相关对象(如&i < &j(void*)pin > (void*)pi)的指针之间的有序比较结果不确定.不能保证任何一个都小于或小于另一个.

Ordered comparisons between pointers to unrelated objects such as &i < &j or (void*)pin > (void*)pi have an unspecified result. Neither is guaranteed to be less or greater than the other.

对于它的价值,您的示例程序在我的系统上输出三个"false"计数.

For what it's worth, your example program outputs three counts of "false" on my system.

这篇关于如果堆栈在数字较低的地址处增长,为什么指针比较会逆转呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆