簡體   English   中英

如何更改作為參數傳遞給函數的變量?

[英]How can i change a variable that is passed to a function as a parameter?

我試圖通過使用返回void的函數來更改結構中的一些變量。 該函數將Struct成員作為參數,結構數組和大小。 該函數具有一些代碼,這些代碼最后更改了struct成員內部的一些變量。 但是,我知道,當您將某些內容作為參數傳遞給函數時,您使用的是副本而不是原始副本。 因此,對struct成員所做的更改將不會“保存”。

我對該主題進行了一些研究,發現指針是解決此問題的一種方法。 但問題是,我不知道如何使用指針,而我發現的解釋有些混亂。

指針是做到這一點的唯一方法嗎? 如果是這樣,有人可以解釋/告訴我如何在這種特定情況下使用指針嗎?

我該如何使用返回void [...]的函數來更改作為參數傳遞給函數的變量[...]

指針是做到這一點的唯一方法嗎?

是。

示例如何執行此操作:

#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已刪除答案 ):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM