views:

508

answers:

5

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
}
+6  A: 

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.

Reed Copsey
+1  A: 

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
}
Jimmy J
+1  A: 

In foo_function x y and z are already pointers (int*), so you can do bar(x, y, z).

+1  A: 
int foo_function(int* x,  int* y, int* z) {
   *x = *y * *z;
   /* x, y and z are pointers to int
      &x, &y and &z are pointers to pointer to int
      bar expects pointers to int, so call bar as:
   */
   bar(x, y, z);
   return 0;
}
dirkgently
+1  A: 

C has no notion of passing by reference. Parameters are always passed by value. However, when using pointers, this value is actually a pointer to your actual value.

But what you are doing with

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

is actually trying to get an address of the pointer, which is essentially meaningless (you would pass an int** instead of an int*).

So,

foo_function(x, y, z);

would be the correct call, as x, y and z are already pointers and you don't need to make the pointing chain any longer :)

Joey