在Linux上,打印功能地址总是打印1(c ++) [英] on Linux, printing function addresses always prints 1 (c++)

查看:147
本文介绍了在Linux上,打印功能地址总是打印1(c ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个处理不同变量和函数的地址的c ++程序。

I'm developing a c++ program that is dealing with addresses for different variables and functions.

当我在基于Linux的操作系统上编译程序时,主要获得1的地址,而不是像其他变量一样的8位数的十六进制数,这在Windows中没有发生。

When I compiled my program on a Linux based OS, all functions including the main get the address of 1 instead of an 8 digit hexa number like other variables, which did not happen in Windows.

我写了这小段代码来解释

I wrote this small piece of code to explain the issue

#include <iostream>
using namespace std;
void Function1();
void Function1()
{
}
int main()
{
int tmp;
void (*a) ()=&Function1;
cout<<a<<endl;
cout<<&Function1<<endl;
cout<<&main<<endl;
return 0;
}

对于所有3个cout调用,输出为1而不是虚拟地址。

for all 3 cout calls, the output is 1 instead of the virtual address.

我非常感谢您的帮助。

感谢提前
Aziz

Thanks in Advance Aziz

推荐答案

指针转换为另一个类型, boolean ,因为它是一个函数指针&对于这些类型的参数,在iostrem库中没有重载 operator (因为有无限数量的这种类型)。指针指向一些非零地址,因为它已经用函数地址初始化 - 所以转换为1(只有0x0地址会给你boolean 0)。

Tthe pointer gets converted to another type, boolean, because it is a function pointer & there is no overloads of operator<< in iostrem library for these types of argument (because there is infinite number of such types). The pointer points to some non-zero address because it has been initialized with address of function - so gets converted to 1 (only 0x0 address would give you boolean 0).

要确认正确的行为,您应该将指针转换为void *,以便您可以使用 operator<< overload void *

To assert correct behavior you should cast the pointer to void* so you can use operator<< overload for void* which is

ostream & operator <<( ostream &, const void * );

示例:

void Function1(){}

int main() {
    void ( *a) () = &Function1;
    cout << ( void*)( a) << endl;
    /* or better - being explicit about harshness of this design */
    cout << reinterpret_cast< void*> ( a) <, endl;
}

http://ideone.com/Fne4Mu

C ++标准n3337 4.12布林转换[conv.bool]

C++ Standard n3337 § 4.12 Boolean conversions [conv.bool]


1算术,无范围枚举,指针或指针的prval $ b到成员类型可以转换为bool类型的prvalue。零
值,空指针值或空成员指针值将
转换为false;任何其他值都将转换为true。
std :: nullptr_t类型的prvalue可以转换为bool类型的prvalue;
的结果值为false。

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

这篇关于在Linux上,打印功能地址总是打印1(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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