0

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.

2
  • Instead of passing c, pass a pointer to c (&c) Commented Apr 27, 2022 at 16:27
  • It may be a poor choice to name a function try. While it is valid in C, it happens to be a C++ keyword, and can cause confusion. Commented Apr 27, 2022 at 16:27

2 Answers 2

1
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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thanks! This is what I was looking for. PS: The "try" was a translation from my language to post here in English lol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.