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

时间:2011-11-22 20:31:23

标签: 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;
}

所需的输出应该是宝贝。

4 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

这不是你想要分配给arr的方式。 它是一个字符缓冲区,因此您应该将字符复制到它:

#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){
  strncpy(arr, "Goodbye,", 8);
}

int main ()
{
  TEST test;
  strcpy(test.arr, "Hello,   world");
  cout << "before: " << test.arr << endl;
  foo(test.arr);
  cout << "after: " << test.arr << endl;
}

http://codepad.org/2Sswt55g

答案 2 :(得分:1)

看起来你正在使用C字符串。在C ++中,您应该考虑使用std::string。在任何情况下,此示例都传递char数组。因此,为了设置宝宝,您需要一次完成一个角色(不要忘记{C>字符串的\0)或查看strncpy()

而不是arr = "baby"尝试strncpy(arr, "baby", strlen("baby"))

答案 3 :(得分:1)

由于上述原因,它不适用于您,但您可以通过添加&amp;作为参考。在该类型的右侧。即使我们至少纠正他,我们也应该回答这个问题。并且它不适合你,因为数组被隐式转换为指针,但它们是r值,并且不能转换为引用。

void foo(char * & arr);