Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by reference through multiple functions

Tags:

c

pointers

Hey all. I'm working on a project for school where I need to pass a few parameters by reference through multiple functions. I understand how I can pass by reference from where the variables are declared to another function, like this:

main() {
  int x = 0;
  int y = 0;
  int z = 0;

  foo_function(&x, &y, &z);
}

int foo_function(int* x, int* y, int* z) {
  *x = *y * *z;
  return 0;
}

However, how would I pass x, y, and z from foo function to another function? Something like this gives me all kinds of compiler warnings.

int foo_function(int* x,  int* y, int* z) {
  *x = *y * *z;
  bar(&x, &y, &z);
  return 0;
}

int bar(int* x, int* y, int* z) {
  //some stuff
}
like image 550
jergason Avatar asked Apr 04 '09 19:04

jergason


2 Answers

Just use:

bar(x, y, z);

X, Y, and Z are already pointers - just pass them directly.

Remember - a pointer is a location in memory. The location doesn't change. When you dereference the pointer (using *x = ...), you are setting the value at that location. But when you pass it into a function, you are just passing the location in memory. You can pass that same location into another function, and it works fine.

like image 59
Reed Copsey Avatar answered Oct 27 '22 03:10

Reed Copsey


You don't need to do anything, they're already references.

int foo_function(int* x,  int* y, int* z) {
  bar(x, y, z);
  return 0;
}

int bar(int* x, int* y, int* z) {
  //some stuff
}
like image 36
Jimmy J Avatar answered Oct 27 '22 05:10

Jimmy J