简体   繁体   English

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

[英]passing struct parameter by reference c++

how can i pass a struct parameter by reference c++, please see below the code. 我如何通过引用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;
}

The desired output should be baby. 所需的输出应该是婴儿。

I would use std::string instead of c arrays in c++ So the code would look like this; 我将使用std :: string代替c ++中的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;
}

That's not how you want to assign to arr. 那不是您要分配给arr的方式。 It's a character buffer, so you should copy characters to it: 这是一个字符缓冲区,因此您应该将字符复制到其中:

#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 http://codepad.org/2Sswt55g

It looks like you are using C-strings. 看起来您正在使用C字符串。 In C++, you should probably look into using std::string . 在C ++中,您可能应该考虑使用std::string In any case, this example is passed a char array. 无论如何,此示例都传递了一个char数组。 So in order to set baby, you will need to do it one character at a time (don't forget \\0 at the end for C-strings) or look into strncpy() . 因此,要设置baby,您将需要一次完成一个字符(不要忘记C字符串结尾处的\\0 )或查看strncpy()

So rather than arr = "baby" try strncpy(arr, "baby", strlen("baby")) 因此,而不是arr = "baby"尝试strncpy(arr, "baby", strlen("baby"))

It won't work for you beause of the reasons above, but you can pass as reference by adding a & to the right of the type. 由于上述原因,它对您不起作用,但是您可以通过在类型的右侧添加&来作为参考传递。 Even if we correct him at least we should answer the question. 即使我们至少纠正了他,我们也应该回答这个问题。 And it wont work for you because arrays are implicitly converted into pointers, but they are r-value, and cannot be converted into reference. 而且它对您不起作用,因为数组被隐式转换为指针,但它们是r值,无法转换为引用。

void foo(char * & arr);

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

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