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 }
Just use:
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.