通过引用传递多个功能 [英] Pass by reference through multiple functions

查看:82
本文介绍了通过引用传递多个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.我正在为一个学校项目工作,我需要通过多个功能通过引用传递一些参数.我了解如何将引用从声明变量的位置传递给另一个函数,例如:

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;
}

但是,如何将x,y和z从foo函数传递给另一个函数?这样的事情给了我各种各样的编译器警告.

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
}

推荐答案

只需使用:

bar(x, y, z);

X,Y和Z已经是指针-只需直接传递它们即可.

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

记住-指针是内存中的位置.位置不变.当取消引用指针时(使用* x = ...),您正在该位置设置值.但是,当您将其传递给函数时,您只是在传递内存中的位置.您可以将相同的位置传递给另一个函数,它可以正常工作.

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.

这篇关于通过引用传递多个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆