通过引用c ++传递struct参数

Car*_*low 1 c++ struct pass-by-reference

如何通过引用c ++传递struct参数,请参见下面的代码.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;
struct TEST
{
  char arr[20];
  int var;
};

void foo(char * arr){
 arr = "baby"; /* here need to set the test.char = "baby" */
}

int main () {
TEST test;
/* here need to pass specific struct parameters, not the entire struct */
foo(test.arr);
cout << test.arr <<endl;
}
Run Code Online (Sandbox Code Playgroud)

所需的输出应该是宝贝.

tun*_*2fs 5

我会在c ++中使用std :: string而不是c数组所以代码看起来像这样;

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;
struct TEST
{
  std::string arr;
  int var;
};

void foo(std::string&  str){
  str = "baby"; /* here need to set the test.char = "baby" */
}

int main () {
  TEST test;
  /* here need to pass specific struct parameters, not the entire struct */
  foo(test.arr);
  cout << test.arr <<endl;
}
Run Code Online (Sandbox Code Playgroud)

  • +1有时最好的答案只是忽略OP的初始尝试并使用适当的C++. (7认同)
  • 我认为这指向C++的最大问题(至少对于初学者来说):语言允许各种垃圾并且不强制执行"正确的C++". (2认同)