1

how can i pass a struct parameter by reference c++, please see below the code.

#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.

Carlitos Overflow
  • 609
  • 3
  • 13
  • 41
  • 2
    It looks like you're learning C + ``, and being told you're learning C++. I'll recommend [a good introductory C++ book](http://stackoverflow.com/q/388242/46642). – R. Martinho Fernandes Nov 22 '11 at 20:54

4 Answers4

5

I would use std::string instead of c arrays in c++ So the code would look like this;

#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;
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
tune2fs
  • 7,605
  • 5
  • 41
  • 57
  • 7
    +1 Sometimes the best answer simply has to ignore the OP's initial attempts and use proper C++. – Kerrek SB Nov 22 '11 at 20:41
  • 2
    I think that points to the biggest problem (at least for beginners) with C++: the language allows all sorts of rubbish and does not enforce "proper C++". – Walter Nov 22 '11 at 22:09
1

That's not how you want to assign to 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

Bill
  • 14,257
  • 4
  • 43
  • 55
1

It looks like you are using C-strings. In C++, you should probably look into using std::string. In any case, this example is passed a char array. 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().

So rather than arr = "baby" try strncpy(arr, "baby", strlen("baby"))

RageD
  • 6,693
  • 4
  • 30
  • 37
1

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.

void foo(char * & arr);
Evan Dark
  • 1,311
  • 7
  • 7