-1

Here I wrote this dummy code to show what my problem (in a more complex code) is. I am using implicit functions with a parameter. The function should assign a new value to the variable passed as a parameter, but I noticed that while this works passing the address of the variable (i.e. the parameter is a pointer, variable i_1 in my code), it won't work passing the variable itself (i_2 in this code). Why does this happen?

#include <stdio.h>
#include <stdlib.h>

void plusfivepointer(int * pa)
 {
  *pa+=5;
 }

void plusfive(int a)
 {
  a+=5;
 }
 

int main(void)
  {
    int i_1, i_2;
    i_1=i_2=0;
    
    printf("i_1=%d i_2=%d\n", i_1, i_2);
    
    plusfivepointer(&i_1);
    plusfive(i_2);
    
    printf("i_1=%d i_2=%d\n", i_1, i_2); //i_2 won't increment
  
    return EXIT_SUCCESS;
  }
 

1 Answers1

0

Because when you don't pass a variable by reference the function creates a local variable with the same name and works the process defined in the function on that local variable and that variable vanishes when the function pop out of the stack. You need to pass by reference to alter the variable you passed in the function.