Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading