How can i change a variable that is passed to a fu

2020-05-10 02:13发布

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?

1条回答
戒情不戒烟
2楼-- · 2020-05-10 02:47

How can i change a variable that is passed to a function as a parameter [...] using a function that returns void [...]

Are pointers the only way to do this?

Yes.

Example how 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);
}

Prints:

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

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;
}
查看更多
登录 后发表回答