如何更改作为参数传递给函数的变量

如何更改作为参数传递给函数的变量

本文介绍了如何更改作为参数传递给函数的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用返回void的函数来更改结构中的某些变量.该函数将Struct成员作为参数,结构数组和大小.该函数具有一些代码,这些代码最后更改了struct成员内部的一些变量.但是,我知道,当您将某些内容作为参数传递给函数时,您使用的是副本而不是原始副本.因此,对struct成员所做的更改将不会被保存".

I am trying to change some variables inside a struct by using a function that returns void. The function takes a Struct member as a parameter, an array of structs and a size. The function has some code, that in the end, changes some variables inside the struct member. However, I know that when you pass something into a function as a parameter, you are working with a copy and not the original. And therefore, the changes that are made to the struct member, will not be "saved".

我已经对该主题进行了一些研究,发现指针是解决此问题的一种方法.但问题是,我不知道如何使用指针,而我发现的解释有些混乱.

I have done some research on the topic, and found that pointers are one way to solve this. The problem is though, i do not know how to use pointers, and the explanations i have found are a bit confusing.

指针是做到这一点的唯一方法吗?如果是这样,有人可以解释/告诉我如何在这种特定情况下使用指针吗?

Are pointers the only way to do this? And if so, can someone explain/show me how to use the pointers in this specific situation?

推荐答案

指针是做到这一点的唯一方法吗?

Are pointers the only way to do this?

是的

示例操作方法:

#include <stdio.h> /* for printf() */

struct S
{
  int i;
  char c;
};

void foo(struct S * ps)
{
  ps->i = 42;
  ps->c = 'x';
}

int main(void)
{
  struct S s = {1, 'a'}; /* In fact the same as:
  struct S s;
  s.i = 1;
  s.c = 'a'
  */

  printf(s.i = %d, s.d = %c\n", s.i, s.c);

  foo(&s);

  printf(s.i = %d, s.d = %c\n", s.i, s.c);
}

打印:

s.i = 1, s.d = a
s.i = 42, s.d = x

另一个示例是(取自/基于 Bruno 的):

Another example would be (taken from/based on Bruno's deleted answer):

void f(int * v1, float * v2)
{
  *v1 = 123; // output variable, the previous value is not used
  *v2 += 1.2; // input-output variable
}

int main(void)
{
  int i = 1;
  float f = 1.;

  f(&i, &f);
  // now i values 123 and f 2.2

  return 0;
}

这篇关于如何更改作为参数传递给函数的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:03