运营商如何<和>使用指针?和>
只是为了好玩,我有一个 const char*
的 std::list
,每个元素都指向一个以 null 结尾的文本字符串,并运行了 std:: list::sort() 就可以了。碰巧的是,它(没有双关语)没有对字符串进行排序。考虑到它正在处理指针,这是有道理的。
根据 std::list::sort( 的 文档 )
,它(默认情况下)使用元素之间的运算符 <
进行比较。
暂时忘记这个列表,我真正的问题是:这些 (>、<、>=、<=) 运算符如何处理 C++ 和 C 中的指针?他们只是比较实际的内存地址吗?
char* p1 = (char*) 0xDAB0BC47;
char* p2 = (char*) 0xBABEC475;
例如,在 32 位小端系统上,p1
> > p2
因为 0xDAB0BC47
> 0xBABEC475
?
测试似乎证实了这一点,但我认为最好将其放在 StackOverflow 上以供将来参考。 C 和 C++ 都做了一些 奇怪的事情到指针,所以你永远不知道......
Just for fun, I had a std::list
of const char*
, each element pointing to a null-terminated text string, and ran a std::list::sort()
on it. As it happens, it sort of (no pun intended) did not sort the strings. Considering that it was working on pointers, that makes sense.
According to the documentation of std::list::sort()
, it (by default) uses the operator <
between the elements to compare.
Forgetting about the list for a moment, my actual question is: How do these (>, <, >=, <=) operators work on pointers in C++ and C? Do they simply compare the actual memory addresses?
char* p1 = (char*) 0xDAB0BC47;
char* p2 = (char*) 0xBABEC475;
e.g. on a 32-bit, little-endian system, p1
> p2
because 0xDAB0BC47
> 0xBABEC475
?
Testing seems to confirm this, but I thought it'd be good to put it on StackOverflow for future reference. C and C++ both do some weird things to pointers, so you never really know...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,不能使用关系运算符来比较任何指针。您只能比较指向同一数组中的元素的两个指针或指向同一对象的成员的两个指针。 (当然,您也可以将指针与其自身进行比较。)
但是,您可以使用 std::less 和其他关系比较函数对象来比较任意两个指针。结果是实现定义的,但保证有总排序。
如果您有一个平面地址空间,则指针比较很可能只是将地址视为整数进行比较。
(我相信 C 中的规则是相同的,没有比较函数对象,但必须有人确认这一点;我对 C 的熟悉程度不如对 C++ 的熟悉程度。)
In C++, you can't compare just any pointers using the relational operators. You can only compare two pointers that point to elements in the same array or two pointers that point to members of the same object. (You can also compare a pointer with itself, of course.)
You can, however, use
std::less
and the other relational comparison function objects to compare any two pointers. The results are implementation-defined, but it is guaranteed that there is a total ordering.If you have a flat address space, it's likely that pointer comparisons just compare addresses as if they are integers.
(I believe the rules are the same in C, without the comparison function objects, but someone will have to confirm that; I'm not nearly as familiar with C as I am with C++.)
这只是一个补充。
在 C++ 20.3.3/8 中:
在 C 6.5.8/5 中:
因此,我认为比较问题中属于两个不同的 '\0' 终止字符串的 char const* 是一种未定义的行为(在 C 中)。
This is just a supplementation.
In C++ 20.3.3/8:
In C 6.5.8/5:
So, I think comparing
char const*
which belong to two different '\0'-terminated-string as in the question is an undefined behavior (in C).是的,他们只是比较内存地址。
Yes, they just compare memory address.