Carlitos Overflow
Carlitos Overflow

Reputation: 683

passing struct parameter by reference c++

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.

Upvotes: 1

Views: 4950

Answers (4)

Evan Dark
Evan Dark

Reputation: 1341

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

Upvotes: 1

tune2fs
tune2fs

Reputation: 7705

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

Upvotes: 5

RageD
RageD

Reputation: 6823

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"))

Upvotes: 1

Bill
Bill

Reputation: 14685

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

Upvotes: 1

Related Questions