gpt4 book ai didi

c++ - C++ 中的指针和函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:05:33 26 4
gpt4 key购买 nike

摘自大学类(class)的讲义,关于“按值调用”:

void fun(int *ip)

{

*ip =100;

}

被调用

int n=2;  

int *np;

np = &n;

fun(np);

would change the value of n to 100.

当我们说“int *ip”时,究竟是什么意思?整数类型的指针?如果是这样,当我们以 np 作为参数调用 fun() 时,不应该出现错误,因为 np 的地址不是整数 n 吗?

然后,我们将 ip 的值更改为 100,那么这是否意味着 n 现在具有地址为 100 的“内存槽”中的值?我确定我错过了什么。 :)

最佳答案

A pointer of type integer?

不,一个指向整数的指针。

when we call fun() with np as its argument, shouldn't there be an error as np has the address of n, which is not an integer?

n 是一个整数,所以没有问题。 &nnpip 在您的代码中都具有相同的类型:int*

And then, we change the value of ip to 100

不……我们改变的是*ip的值,而不是ip的值。也就是说,我们更改 ip 指向 的值(有时也称为 pointee)。

关于c++ - C++ 中的指针和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2097418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com