search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

1 answers
Q&A C传址调用,两次修改*a的值,返回结果是第一个*a

0

这是C代码。

#include void func(int *a){
    *a = 2;    
    int c = 3;    int *b = &c;
    a = b;
    
    *a = 3;
}void main(){    int a = 1;
    func(&a);    printf("%d\n", a);
}

运行结果是

2

为什么a的结果不是3呢?


Your Answer
submit

1 answers
0

在func函数中,你可以将int *a写成int* a,这样就一目了然了,a是形参。一开始,a的值是main函数里a的地址。这样我们把func形参a换个名字,就叫做d吧。这样整个函数就变成这样了:

void func(int* d){
    *d = 2;    
    int c = 3;    int* b = &c;
    d = b;
    
    *d = 3;
}

好了我们再来看。一开始d是a的地址。所以*d赋值就是给a赋值。但是,b是c的地址,d = b,d就变成c的地址了,那么给*d赋值就是给c赋值了,和a就没有什么关系了。所以只被赋值了第一次。

不知道这样你懂了没,我不善表达,见谅。


2016-11-08 15:44:48

submit

Popular tool

vc9-vc14 (32+64 bit) runtime library collection (link below)

vc9-vc14 (32+64 bit) runtime library collection (link below)

Download the collection of runtime libraries required for phpStudy installation

VC9 32-bit

VC9 32-bit

VC9 32-bit phpstudy integrated installation environment runtime library

PHP programmer toolbox full version

PHP programmer toolbox full version

Programmer Toolbox v1.0 PHP Integrated Environment

VC11 32-bit

VC11 32-bit

VC11 32-bit phpstudy integrated installation environment runtime library

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use