Home > Enterprise >  Pointers and variables assignment basic
Pointers and variables assignment basic

Time:04-28

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.

CodePudding user response:

int c = 3;


void pass_by_ref(int *a)  // Take a Pointer to an integer variable
{
      (*a);               // Increment the value stored at that pointer.
}

int main(){
  pass_by_ref(&c);        // Pass the address of the variable to change
  printf("%d\n",c);
  return 0;
}

CodePudding user response:

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

  • Related