开发者

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. 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 kn开发者_如何学运维ow how these pointers work through other functions


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'. Essentially, it passes in the exact memory location of variable1 in your main function. When you want to change that, you need to dereference by putting an asterix "*variable1 += 6". The dereference says 'now modify the int stored at this pointer'.

When you use the asterix in your function def, it means that 'this will be a pointer to an 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;, it was almost right...as is you just added 1 to the pointer, which vanished as soon as add() returned...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜