views:

154

answers:

3

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 know how these pointers work through other functions

+1  A: 

...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...

DigitalRoss
+6  A: 

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)
Kieveli
it is still printing 5 ??
Supernovah
aparently, add can't be void ?? any idea about that
Supernovah
+4  A: 

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)
Mads Elvheim
that was just a typo (part 2) thx
Supernovah