Search code examples
cfunctionpointersvariablesassign

Pointers and variables assignment basic


I'm trying to understand the basic of pointers, and done this code:

int c = 3;
int try(int a){
  ++a;
  return 0;
}
int main(){
  try(c);
  printf("%d\n",c);
  return 0;
}

How do I manage to print 4 with pointers? I know that I can do it like this:

int c = 3;
int try(int a){
  ++a;
  return a;
}
int main(){
  c = try(c);
  printf("%d\n",c);
  return 0;
}

but I really want to learn how to pass those values through functions via pointers.

Furthermore, any great book recommendation for solid C learning is always welcome. Thanks in advance.


Solution

  • This is how to do 'c style pass by reference'

    int tryIt(int *a){
      ++(*a);
    }
    int main(){
      int c = 3;
      tryIt(&c);
      printf("%d\n",c);
      return 0;
    }
    

    You pass a pointer to the variable and the dereference the pointer in the function. The function effectively 'reaches out ' of its scope to modify the passed variable

    Note that I moved c into main. In your original code 'try' could have modified c itself since its at global scope.

    And changed 'try' to 'tryIt' - cos that looks weird