通过多个function通过引用传递
大家好。 我正在为学校做一个项目,我需要通过多个函数通过引用传递一些参数。 我理解如何通过引用将变量声明的位置传递给另一个函数,如下所示:
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; }
但是,如何将foo函数中的x,y和z传递给另一个函数? 这样的东西给了我各种编译器警告。
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 }
只需使用:
bar(x, y, z);
X,Y和Z已经是指针 – 只是直接传递它们。
记住 – 指针是内存中的一个位置。 位置不会改变。 取消引用指针(使用* x = …)时,您将在该位置设置值。 但是当你将它传递给一个函数时,你只是在内存中传递该位置。 您可以将相同的位置传递到另一个函数,它工作正常。
你不需要做任何事情,他们已经引用了。
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 }
在foo_function中,xy和z已经是指针(int *),所以你可以做bar(x,y,z)。
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; }
C没有通过引用传递的概念。 参数始终按值传递。 但是,在使用指针时,此值实际上是指向实际值的指针。
但是你在做什么
foo_function(&x, &y, &z);
实际上是试图获取指针的地址,这实际上是没有意义的(你会传递一个int**
而不是一个int*
)。
所以,
foo_function(x, y, z);
将是正确的调用,因为x
, y
和z
已经是指针,你不需要再做指点链了:)