passing struct parameter by reference c++ - 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.

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

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

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

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

Related

Request for member 'end' in 'arrPtr' etc

I am trying to pass an array of strings off to a function so that it will sort it along with a Class Template array object of strings which I don't even know what that would look like. But as it is right now. When I use size() inside of main it works just fine but when I use size() inside a function I am typing up it throws out this error.
#include <iostream>
#include <iomanip>
#include <array>
#include <string>
#include <algorithm> // contains sort and binary_search
using namespace std;
void sortArrays(string arr[]);
int main()
{
array<string, 5> hello = {"Hello", "world", "How", "Are", "You"};
sortArrays(&hello[0]);
}
void sortArrays(string array[])
{
string *arrPtr = array;
sort(*arrPtr.begin(), *arrPtr.end());
cout << endl << endl;
}
Like this, std::array it's easy to pass by reference.
#include <algorithm>
#include <array>
#include <iostream>
#include <vector>
#include <string>
void sortArray(std::array<std::string,5>& arr)
{
std::sort(arr.begin(),arr.end());
}
int main()
{
std::array<std::string, 5> hello = { "Hello", "world", "How", "Are", "You" };
sortArray(hello);
for (const auto& str : hello)
{
std::cout << str << " ";
}
std::cout << std::endl;
}

anyone know how to initialize an empty array

Anyone know how to Initialise the array of car registration structures by placing a “Empty” in the car registration number of each array element.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car;
{
string car_reg = 0;
char car_manuf[30];
char car_model[30];
double price;
string car_reg{};
}
}
need some h3elp
Explanation inline.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car // removed ; the ; terminates the definition, cutting it off
// and leaving you with a declaration. Everything in the braces
// that follow would be seen as a block of code defining two
// automatic variables scoped inside the block. Useless in this
// case.
{
string car_reg = 0; // this is actually NASTY! More on it later
char car_manuf[30] = "EMPTY"; // assigns default value. But only if your
// compiler comes from this decade.
// If you are rocking an antique you can't
// do this. Will cover what you can do below.
char car_model[30] = "EMPTY";
string car_reg{}; // cannot reuse the car_reg identifier in the same scope
// car_reg is either a variable or a function.
}; // ; goes here
car c; // for testing purposes
cout << c.car_manuf << ',' << c.car_model; // for testing
}
string car_reg = 0; is nasty. What it does is defines a member variable car_reg and uses 0 as the default. The 0 is converted to a null pointer to a char array. The string constructor attempts to initialize from a null pointer and blows up at runtime. The compiler is just fine with this bit of stupidity because in the old days NULL could be #define NULL 0 and we don't want to break decades of old code by fixing this problem.
Since we can't do default initializations in pre C++11 code we need a constructor to do the work. Yup. structs can have constructors. This is because a struct and a class are almost identical. The only difference you're ever likely to see between the two is class defaults to private access and structs default to public access.
struct car
{
char car_manuf[30];
char car_model[30];
car (): car_manuf("EMPTY"), car_model("EMPTY")
{
}
};
Note that his isn't as groovy as it looks. You're usually better off with something like
struct car
{
string car_manuf;
string car_model;
car (const string & manuf,
const string & model): car_manuf(manuf), car_model(model)
{
}
};
and not allowing the empty case at all. When possible force users to initialize a class into a fully initialized state. And use std::string. Very handy tool, std::string.
Note that
struct car
{
char car_manuf[30];
char car_model[30];
car (const char * manuf,
const char * model):
car_manuf(manuf), car_model(model) // fails to compile
{
}
};
is not possible. You can't initialize a char array with a pointer to char. I'm not entirely certain why the language doesn't have a rule to handle this, but it doesn't. If forced to use char arrays,
struct car
{
char car_manuf[30];
char car_model[30];
car (const char * manuf,
const char * model)
{
strcpy(car_manuf, manuf);
strcpy(car_model, model);
}
};
and make dang sure that manuf and model will fit in 29 characters or less.
Have you tried a simple for loop, to fill (for example) the char_model array with zeros?
....
char car_model[30];
/* Adding the for loop here (it will fill car_model's elements with zeros*/
for(int i=0; i<=sizeof(car_model); i++){
car_model[i]=0;
....
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car
{
string car_reg = {"Empty"};
char car_manuf[30];
char car_model[30];
car(const char* manuf,
const char* model)
{
strcpy(car_manuf, manuf);
strcpy(car_model, model);
}
};
}

When do you use which method to get variables from another file?

I am currently learning C++ and found that there are at least two ways using variables defined in other files. However I do not understand really, when to use what method.
For example:
I have writte in "h1.h":
extern int k;
and "a2.cpp" writes:
#include "a2.h"
#include "h1.h"
int k = 42;
int k2 = 43;
Then I can reference k in my main.cpp with:
#include "main.h"
#include "a1.h"
#include "h1.h"
#include <iostream>
Main::Main() {}
int main() {
std::cout << k << std::endl;
}
However if I want to use k2 in main.cpp I could simply write a getter/setter method, thereby I would avoid having to use extern in a common included header file.
I would like to know: What are other ways to access variables from other files? When do you use which method (and why )?
You expose k as a function, or not at all, not as a variable.
"h1.h":
int k();
void k2(int &);
"h1.cpp":
int k() { return 42; }
void k2(int & value) { value = 43; }
"main.cpp"
#include "h1.h"
#include <iostream>
int main () {
std::cout << k() << std::endl;
int any_name;
k2(any_name);
std::cout << any_name << std::endl;
}

BOOST_PP_REPEAT with boost::fusion::size

I want to iterate in compile time over struct and write to output number of iteration. Just to mention - in real case I will pass some more parameters in data.
#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
struct MyStruct
{
int x;
int y;
};
BOOST_FUSION_ADAPT_STRUCT(
MyStruct,
(int, x)
(int, y)
)
#define PRINT(unused, number, data) \
std::cout << number << std::endl;
int main()
{
MyStruct s;
std::cout << boost::fusion::size(s) << std::endl;
//line below works - it iterate and write output
BOOST_PP_REPEAT(2, PRINT, "here I will pass my data")
//this won't compile
//BOOST_PP_REPEAT(boost::fusion::size(s), PRINT, "here i will pass my data")
}
How to fix problematic line so it will work when I will add more members in structure? I need solution for C++03 :(
Instead of using BOOST_PP_REPEAT, you can use the boost::fusion::for_each which goes through every element. example:
#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
struct MyStruct {
int x;
int y;
};
BOOST_FUSION_ADAPT_STRUCT(
MyStruct,
(int, x)
(int, y)
)
template<typename Data>
struct PrintWithData {
PrintWithData(Data data) : data(data) {}
template<typename T>
operator()(const T& thingToBePrinted)
{
std::cout << thingToBePrinted << std::endl;
}
Data data;
};
int main()
{
MyStruct s;
//this will compile
boost::fusion::for_each(s, PrintWithData<std::string>("here I will pass my data"));
}
Here is exact solution for this problem (asked more general question later, and found answear which solve this problem too): https://stackoverflow.com/a/31713778/4555790

Passing vector by reference in boost::bind

Why is the output of this 0?
http://ideone.com/S7hgv
#include <boost/bind.hpp>
#include <vector>
#include <iostream>
using namespace std;
void f2(vector<int> &h)
{
h.clear();
h.push_back(0);
}
void f1(vector<int> &h)
{
boost::bind(f2, boost::ref(h));
}
int main()
{
vector<int> h;
f1(h);
cout << h.size() << "\n";
}
I need it to be 1, and for some reason h is not modified.
boost/std::bind() only constructs the function object. You still have to call it, in order for any code inside to execute.
To get the output of 1, replace the line
boost::bind(f2, boost::ref(h));
with
boost::bind(f2, boost::ref(h))();