简体   繁体   English

指针作为C中的函数参数

[英]Pointers as function parameters in C

I am having trouble getting this to work. 我很难让它工作。

I have variables initiated in main which I want to pass onto other functions and have changed. 我在main中初始化了一些变量,希望将这些变量传递给其他函数并进行了更改。 I know the only way this can be done is with pointers or to declare the variables outside the main function. 我知道可以做到这一点的唯一方法是使用指针或在主函数外部声明变量。 I would prefer to use pointers 我宁愿使用指针

How is it done? 怎么做?

eg 例如

int main(){
    int variable1 = 5;
    add(&variable1, 6);
    printf("%d", variable1);

    return 0;
}

int add(int *variable1, int addValue){
    variable1 += addValue;

    return 0;
}

I want to print 11 but I don't know how these pointers work through other functions 我想打印11,但不知道这些指针如何通过其他功能工作

You simply need to dereference your pointer: 您只需要取消引用指针即可:

void add(int *variable1, int addValue)
{
    *variable1 += addValue;
}

In your function call, you pass in "&variable1" which means 'a pointer to this variable'. 在函数调用中,您传入“&variable1”,这意味着“指向此变量的指针”。 Essentially, it passes in the exact memory location of variable1 in your main function. 本质上,它在您的主函数中传递变量1的确切存储位置。 When you want to change that, you need to dereference by putting an asterix "*variable1 += 6". 当您要更改它时,需要通过添加星号“ * variable1 + = 6”来取消引用。 The dereference says 'now modify the int stored at this pointer'. 取消引用表示“现在修改存储在此指针处的int”。

When you use the asterix in your function def, it means that 'this will be a pointer to an int'. 在函数def中使用星号时,表示“这将是一个指向int的指针”。 The asterix is used to mean two different things. 星号用于表示两种不同的含义。 Hope this helps! 希望这可以帮助!

Oh, and also add the explicit type to the function call: 哦,还要在函数调用中添加显式类型:

void add(int *variable1, int addValue)

You simply forgot to dereference the pointer: 您只是忘了取消引用指针:

*variable1 += addValue;

And all the function parameters must have an explicit type. 并且所有函数参数都必须具有显式类型。

void add(int *variable1, int addValue)

...you just need *variable1 = addvalue; ...您只需要*variable1 = addvalue; , it was almost right...as is you just added 1 to the pointer, which vanished as soon as add() returned... ,这几乎是正确的...因为您刚刚将1加到了指针,当add()返回时该指针就消失了...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM