Change variable by call to function

3

I need to know if this can be done, I think with pointers it could be but I do not know what form. On the one hand we have a function cambiarValor

void cambiarValor (int a){
    a=a*4;
}

and on the other hand the main from where we invoke it

int main(){
    a=4;
    cambiarValor(a);
}

What I want to know is so that at the end of main the value of a has changed which pointers I have to use

    
asked by hugoboss 09.05.2018 в 12:31
source

1 answer

7
  

What I want to know is so that at the end of main the value of a has changed which pointers I have to use

This, better explained, would look like this:

  

What I want to know is what do I have to change in my code to change the value of a

And, indeed, the solution is to use pointers.

To begin with, the cambiarValor function must receive a pointer (this is the only way to get the function to modify a variable outside the function itself):

void cambiarValor (int* a){
    *a=(*a)*4;
}

And, finally, we have to modify the main so that the variable does not pass by value but now to cambiarValor we must provide a reference to said variable:

int main(){
    a=4;
    cambiarValor(&a);
}
    
answered by 09.05.2018 / 12:40
source