简体   繁体   English

在 C function 中将结构作为参数传递

[英]Passing structure as argument in C function

typedef struct { int b, p; } A;
void f(A c);
int main()
{
  int i;
  A a = {1,2};
  f(a);
  printf("%d,%d\n",a.b,a.p);
  return 0;
}
void f(A c)
{
  int j;
  c.b += 1;
  c.p += 2;
}

In the following code, why is it that ab and ap are still 1 and 2 even after being passed through f(a), which should change them to 2 and 3?在下面的代码中,为什么 ab 和 ap 经过 f(a) 后仍然是 1 和 2,这应该将它们改为 2 和 3?

What you are using is called call by value, in call by value the changes you are doing to function arguments will not be reflected in the caller, for that you need call by reference您正在使用的称为按值调用,在按值调用中,您对 function arguments 所做的更改不会反映在调用者中,因为您需要按引用调用

typedef struct { int b, p; } A;

void f(A c);

void f2(A *c);

int main()
{
  int i;
  A a = {1,2};

  // call by value
  f(a);
  printf("%d,%d\n",a.b,a.p);

  //call by referecne    
  f2(&a);

  printf("%d,%d\n",a.b,a.p);
  return 0;
}

void f(A c)
{
  int j;
  c.b += 1;
  c.p += 2;
}

void f2(A *c)
{
  int j;
  c->b += 1;
  c->p += 2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM