首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >传递一个指向函数的指针--为什么我不能打印地址?

传递一个指向函数的指针--为什么我不能打印地址?
EN

Stack Overflow用户
提问于 2017-08-26 08:00:53
回答 4查看 145关注 0票数 3

我不明白为什么我不能打印指针的地址。我知道理解指针是非常基础的,所以任何帮助都是非常感谢的。

代码语言:javascript
复制
void printp(int& test)
{
        cout << test << endl;
}

int main()
{
        int *p = new int;
        *p = 1;
        int np = 0;

//      printp(p);  // why doesn't this print the address of p?
//      printp(&p); // why doesn't this print the address of p?
        printp(*p); // prints 1
        printp(np); // prints 0

return 0;
}

当我尝试使用'printp(p)‘时,我得到了下面的错误。

代码语言:javascript
复制
test.cpp: In function ‘int main()’:
test.cpp:17:10: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  printp(p);  // why doesn't this print the address of p?
          ^
test.cpp:5:6: note:   initializing argument 1 of ‘void printp(int&)’
 void printp(int& test)
      ^~~~~~
test.cpp:17:10: error: cannot bind rvalue ‘(int)p’ to ‘int&’
  printp(p);  // why doesn't this print the address of p?
EN

回答 4

Stack Overflow用户

发布于 2017-08-26 08:12:06

您从编译器获得错误消息,因为编译器需要引用参数的确切类型。

当函数有引用参数时

代码语言:javascript
复制
void printp(int& test);

代替指针参数,

代码语言:javascript
复制
void printp(int* test);

调用方必须提供确切类型的变量。它不能提供对任何其他类型的变量的引用(除非您可以从另一种类型dynamic_cast到参数的类型)。

因此,当您调用printp(p);时,编译器要求p的类型为int,而不是int *

如果您通过值传递,编译器将为您提升或static_cast某些类型。

代码语言:javascript
复制
void printp(int test);
short s = 0;
printp( s ); // s is promoted to int here.

但是,当参数是引用时,编译器不能为您做这件事。

票数 8
EN

Stack Overflow用户

发布于 2017-08-26 08:13:45

在你的代码中,printp(int&)是一个接受引用而不是指针的函数,所以在你的例子中,要获得指针的地址,你可以简单地改变它或重载它:

代码语言:javascript
复制
void printp(int* test){
    cout << test << endl; // the addres test contains not its address
    cout << &test << endl; // the address of test itself
    cout << *test << endl; // the value in the address that test points to
}

在main中:

代码语言:javascript
复制
printp(p);

输出:

代码语言:javascript
复制
00893250
0018FEEC
1
票数 2
EN

Stack Overflow用户

发布于 2017-08-26 08:40:42

对于int a;

代码语言:javascript
复制
expr | type
-----+-----
&a   | int*
a    | int
*a   | - (not valid)

对于int* p;

代码语言:javascript
复制
expr   | type
-------+-----
&p   | int**
p    | int*
*p   | int
**p  | - (not valid)

对于int** pp;

代码语言:javascript
复制
expr   | type
-------+-----
&pp   | int***
pp    | int**
*pp   | int*
**pp  | int
***pp | - (not valid)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45890732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档