C++ :: Passing Array Of Variables By Reference?

Sep 10, 2014

I define an integer variable and pass it by reference to a function.

int func(int &x)
{
// do something
}
int x;
func(x);

However, I have not only one variable but an array of variables with its predefined name. How do I pass to the function by using loop? Example:

int x, y, z;
func(x);
func(y);
func(z);

How can I do this by using loop?

View 7 Replies


ADVERTISEMENT

C++ :: Passing STL Array By Reference

Dec 31, 2012

How can I pass a matrix as a reference parameter? I am using the following declarations:

Code:
typedef std::vector< std::vector<std::string> > ss_matrix_t;

I declare the matrix with the following statement, where nRows and nCols are integers

Code:
std::vector< std::vector<std::string> > vI2Matrix(nRows, std::vector<std::string>(nCols,""));

The function is called with:

Code:
int read_files(std::string fname, int nCols, int nRows, ss_matrix_t &ssMat )

But I get a linker error:

error LNK2019: unresolved external symbol "int __cdecl read_splayed_files(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int,int,class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > >,class std::vector<class std::vector<class

[Code] ....

I suspect the syntax of the declaration, but I am not sure what to do here? If I change the call to the function, then the array ( matrix ) is passed by value, and it takes forever:

Code:
int read_files(std::string fname, int nCols, int nRows, ss_matrix_t ssMat )
// this takes ages ( it does compile and link )

View 14 Replies View Related

C/C++ :: Does Passing Array By Reference Create Tight Coupling

Dec 30, 2014

When you pass an entire array as an argument into a function, it passes by reference. When you modify the reference in the function, it also modifies the value in the calling function, even without returning a value. This is because references edit the same memory address, rather than creating a copy of it (passing by value).

This code shows an example of an array being passed by reference into a function, being modified, and printed out back in the main function:

void myFunction(int refArray[], const int valMAX_ARRAY) {
int x = 0;
while (x < valMAX_ARRAY) {
refArray[x] = refArray[x] * 3;
++x;

[code]....

OUTPUT

33
99
135

Coupling is how much multiple functions depend on the same variables. When using globals for instance, the program may become error-prone or difficult to follow if many different functions can modify the same values.

My question is this - Doesn't tight coupling occur when passing arguments by reference? If you pass the same array to multiple functions, all functions are modifying the same information. Isn't this the same as working with globals?

Second question - Since arguments being passed by value will "copy" a memory address rather than allow the function to modify the same information, isn't this bad on performance? Isn't it the same as initializing new variables within the body of the function? Doesn't this create more memory offsets every time the function is run?

View 3 Replies View Related

C++ :: Using Pointers Instead Of Reference Variables In Function

Mar 26, 2013

The following function uses reference variables as parameters. Rewrite the function so it uses pointers instead of reference variables, and then demonstrate the function in a complete program.

int doSomething(int &x, int &y)
{
int temp =x;
x = y * 10;
y = temp * 10;
return x + y;
}

I understand how to covert the reference variables to pointers, however I am stuck on this error. Either I get the error listed in the title or (with a few changes) the error "invalid conversion from 'int' to 'int*'"

What am I doing incorrectly?

#include <iostream>
using namespace std;

int doSomething(int*, int*);

int main(){
int X, Y, result;

[Code] ....

I have multiplied both x and y by 10 and then added them together!

Here is the result " //I really didn't know how else to use the "doSomething" function in a meaningful way. So... I just stated what the function does.

<< result << ".
";
system("PAUSE");
return 0;
}
int doSomthing(int *x, int *y)

[Code] .....

View 1 Replies View Related

C++ :: Passing A Reference Of Arg (boost Lib)

Dec 19, 2013

I have in my main(), a function that creates my arg object using boost/program_options.hpp i want to pass this object to another function using templates like this:

Code:
template <typename Targ>
void Count(Targ & arg){
MyObj<string> QueryTab(arg["input-file"].as<string>()); //line number is 352
...
}

However I get an error:

Code:
../include/Filter.hpp: In member function ‘void Count(Targ&)’:
../include/Filter.hpp:352:40: error: expected primary-expression before ‘>’ token
../include/Filter.hpp:352:42: error: expected primary-expression before ‘)’ token
... obviously it does not recognize my intention, what did I do wrong?

View 2 Replies View Related

C++ :: Passing By Reference With Templates

Aug 26, 2014

Why wouldn't this code compile when adding '<double>' after the function call?

template<class T>
T add(T& a, T& b){
return a + b;
}
int main() {
int a, b;
cin >> a >> b;
cout << add<double>(a,b);
}

Compiler error:
cannot convert 'a' (type 'int') to type 'double&'

View 2 Replies View Related

C++ :: Passing Classes By Reference?

Mar 1, 2013

I make a class (it stands for an ARMA time series), and I have a method wich modifies some of its variables. In other part of my program I have a function wich receives one object of this class as a parameter and, at some point, it calls the method of the ARMA class to modify it; here is my deal I want to pass the ARMA class by reference to this function, because I want the variables of the instance I'm passing to be modified, not those of a copy the method uses. Also, I would like not to declare the function inside the class ARMA, cause I use it in other places too (it's basically a Nelder-Mead optimization what it performs).

Here is a code wich sketches what I've been trying, and exactly the error message I get is "modifyParameter has not been declared".

#include <iostream>
#include <cstdlib>
using namespace std;
class ARMA{

[code]....

View 5 Replies View Related

C++ :: Passing A Stack By Reference?

Feb 21, 2012

I'm having trouble using a stack's functions when passing it by reference.

I'm currently messing around with passing a pointer to the stack instead, but to no avail.

The problem is in my placeInto function. I will label, in my code, where the program stops.

The program is an RPN Calculator, designed to receive keyboard input of an infix mathematical string, convert the infix string into a postfix mathematical string, and then solve the string. The program then outputs the postfix string and the solution.

The program loops through until closed via force-close, as was assigned.

*/
#include <iostream>
#include <string>
#include <stack>
using namespace std;
///////////////////////
// function prototypes //
///////////////////////
// u = unfinished
/* 1*/void welcome(); // welcome screen

[code]....

View 3 Replies View Related

C/C++ :: How To Make A Function Prototype That Uses Variables By Reference

Dec 4, 2014

How to how to make a function prototype that uses variables by reference. I'm making a decision based game where two running totals of two variables (ending and morality from decisions made) will decide the game outcome. I only have a few modules put in so far and most of the "story" parts cut down here to save space. I'm also getting an error saying there is more than one instance of overloaded function for the "whatToDo" module.

// ZombieGame.cpp : Defines the entry point for the console application.
//
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream>
using namespace std;
//These are function prototypes to declare the functions being used
void WakeyWakey();
void TwentyMinsLater(int);

[Code] .....

View 2 Replies View Related

C++ :: Calling Destructors And Passing By Reference

Jun 5, 2014

Every time we pass an object to a function, and when the function ends and the object is not necessary anymore the destructor is called. if it's passing by value then a copy of the object is passed. if the object has a pointer inside of it so we implement the copy constructor to create a new pointed-variable so the original pointer will not get deleted.

so far so good. But what about passing an object to a non-member function by reference?

The language says that as soon as the function ends - the object will be deleted , because we passed by ref. that means that after the function ends - the object is not usable anymore! =What does that say? that in c++ you can't pass object by ref. because it will get deleted and un-uasable??

Varifying it with a compiler shows that the object is NOT deleted after the function ends.

View 10 Replies View Related

C++ :: Passing String Using Reference Operator

Aug 28, 2014

Why it is necessary to use the reference operator here ?

const string& content() const {return data;}

Example in [URL] ....

// classes and default constructors
#include <iostream>
#include <string>
using namespace std;

class Example3 {
string data;

[Code] .....

View 2 Replies View Related

C++ :: Passing Pointers By Reference To Function?

Mar 4, 2013

If f1 and f2 are two user defined functions.

main(){
int *p;
f1(&p)
}
f1(**p){
f2(&p);//

If I've to pass the pointer by reference again in another function, will I've to do something like this?

}
f2(***p){
**p = NULL;
}

View 3 Replies View Related

C/C++ :: Passing A Stream Object By Reference?

May 5, 2014

I need to create a function in my program to open an input file and another function to open an output file and I need to use the files in other functions so Im trying to pass the stream object by reference but then i need a condition that tells the compiler not to reopen the file because then it will delete everything and make me input the file names again. Heres the two functions.

void InputFileOpen(ifstream &inFile) {
string file_name;
if(!inFile.is_open()){
cout<< "Enter the input file name: ";
cin>> file_name;
inFile.open(file_name, ios::in);

[code]....

View 4 Replies View Related

C++ :: Error Passing Object Reference

Nov 23, 2013

Code:

#include <Data.h>
int main(int arg_count, char** argv) {
if(arg_count!=3){
cerr<<"Files misisng
";
exit(1);

[code]...

This actually should work, because it is passing address of polymorphisms object.I have tried changing prototype of test in Data.h, but failed.passing object address/pointers in C++.

View 5 Replies View Related

C++ :: Passing A Function Parameter By Reference?

Sep 25, 2012

I created the following code to pass the the variable 'inputVoltage' by reference to the function 'input'. It certainly works when I run the program, but I dont think it is a standard way of doing it, i.e. the use of '*' and '&' is not according to convention ? Or perhaps the way did it is acceptable ?

int input (double *inputVoltage);
int main ( {
double inputVoltage;
input(&inputVoltage);

[Code]....

View 2 Replies View Related

C++ :: Passing Sub-range Of A Vector By Reference

Dec 18, 2012

Suppose I have a stl vector of ints, and I want to pass a sub-range of that vector as an argument to a function. One way of doing that would be to copy the sub-range, and then pass that copy by reference, as follows:

Code:
#include <vector>
using namespace std;
int MyFunction(vector<int> &a_vector) {
// Do something
return 0;

[Code] ....

However, it can be time-consuming to copy the elements between the two vectors if my_vector is large. So I'm wondering if it is possible to directly pass a sub-range of my_vector by reference, without having to create a new vector and manually copy over all of the relevant elements?

View 4 Replies View Related

C/C++ :: Passing By Value With Two Variables

Jun 24, 2014

This is my first time working with C++ and I have put together this program and came up with two errors and I am unsure what it is wanting me to do. The errors I got are:

1>c:usersownerdocumentsvisual studio 2010projectsweek5week5passing_by_value.cpp(30): error C2064: term does not evaluate to a function taking 1 arguments
1>c:usersownerdocumentsvisual studio 2010projectsweek5week5passing_by_value.cpp(38): error C2064: term does not evaluate to a function taking 1 arguments

#include<iostream>
using std::cin;
using std::cout;
using std::endl;

[Code].....

View 6 Replies View Related

C++ :: Passing Vectors To Functions As Arguments By Reference And Value

Mar 12, 2014

I have a program that is working very well when I pass C++ vectors as arguments to my functions by reference, but I get some compilation errors when try to make a modification. I am also posting the entire program and its output below. so that you can see what is going on. I have commented out the line that causes an error.(Some of the indentation that got corrupted when I copied the code to the browser.)

This program basically calculates the coefficients of a least square polynomial and then evaluates this polynomial at artificial data points and verifies that this actually reproduces the original data within reasonable floating point error.

The function that computes the coefficients of the least square polynomial is Code: vector<double> LSPVecValued_GSL( const int, const vector<float> &, const vector<float> &); and as you can see it returns a vector by value, and this vector contains the coefficients of the least square polynomial.

There is also a function that evaluates this polynomial by accepting a vector argument by reference : Code: float evaluate_polynomial(double, vector<double>& ) ; I have also created another version of the evaluation function which accepts the same vector argument by value: Code: float evaluate_polynomial_ByValue(double t, vector<double> vec_a) ; In the program I call the first evaluation function (whose vector argument is passed by reference) by first using an intermediate vector variable containing the coefficients, and then I pass this vector as an argument to the evaluation function, as follows:

Code:
vec_a = LSPVecValued_GSL( deg, vec_x , vec_y);
for(int j=0; j< n ; j=j+20 ) {
cout<<"x["<<j<<"] = " << vec_x[j] << " ,y["<<j<<"] = " << vec_y[j] <<" , p(x["<<j<<"]) ( EVALUATED FROM REFERENCE) = "
<< evaluate_polynomial( vec_x[j], vec_a) << endl; // This version works without error

[Code] .....

As you can see above, I am also able to call the second evaluation function (the one whose vector argument is passed by value) directly by plugging in the function LSPVecValued_GSL"(...)" and this works without error, and this is a one step process, only one line of code is involved.

However, I get a compilation error (line number 12 that I have commented out above) if I try to plug in the function "LSPVecValued_GSL(...)" into the first evaluation function that expects a vector argument by reference. I tried to put a "&" in front ofLSPVecValued_GSL but this did not fix the bug.

What syntax is appropriate to use the first evaluation function (which accepts a vector argument by reference) if I want to plug in the vector-valued function LeastSquarePolynomial_GSL directly in the the first version of the evaluation function which expects a vector argument by reference?

View 14 Replies View Related

C++ :: Passing Struct Arrays To A Function By Value Not By Reference?

Mar 16, 2013

I am working on incorporating a function in to an already existing piece of code, I have incorporated the function fine as far as I am aware.

The problem I have is that I am trying to pass two int arrays to the function, so that i can manipulate and compare them "the values will be changed the originals cannot be changed"

I am having trouble pulling the information out of the already created array, I am able to pass the pointer reference for the single value which is not exactly what i want "best_prog".

My function is below I have commented the memcpy parts and also the majority of the code isn't there cause it is not needed to see make the copy work.

int edit_distance(int index) {
struct prog *progp = &population[best_prog];
/* The struct of best prog not sure if i need one for the other prog I am trying to compare it with the one below doesn't work as intended.*/
//struct prog *progp = &population[];
int editdistance = 0, ar1 = 0, ar2 = 0, a = 0, b = 0, j = 0, x = 0;

[code].....

View 12 Replies View Related

C/C++ :: Passing Vector As Reference Memory Leak?

Nov 30, 2014

I asked a few questions a few weeks ago about vectors and the fact that their data is stored on the heap. When a function closes, anything in its scope is destroyed, if it's passed by reference it won't be destroyed since it's outside the scope.

I have a program where I create a vector in one function, then pass it by reference to another. When I test for memory leaks, I get told I have 1 memory leak in in my start() function, and one memory leak in my save() function.

It's just a simple program that creates a vector, populates it with some numbers, then saves the numbers in a file. If I'm passing my vector by reference to another function, do I need to manually do something to avoid memory leaks? I'll post the code below.

#include <vector>
#include <iostream>
#include <iomanip>
#include <cmath>

[Code].....

View 2 Replies View Related

C# :: Reference Type When Passing Struct To Parameter?

Jan 24, 2015

Does putting a ref when passing a struct to a parameter work? Say i have this code

struct struct1 {
public int i;
public void show() {
Console.WriteLine(i);

[Code] ....

The output doesn't change. The result is

0
100
500
0

View 1 Replies View Related

C :: Passing Variables Among Functions

Mar 6, 2015

I have this code where I am trying to retrieve the contents of the variable dev1 and dev2. for some reason when i compile and run I am getting 0 and 0.

Code:

typedef struct {
uint32_t x;
uint32_t y;
} sample;
void get_sample(sample *one)

[Code].....

View 9 Replies View Related

C++ :: Passing Variables Into A Function

Mar 29, 2014

ok I have a class Player with lots of variables and im gonna call a function to checkXp, if I call it with the whole player object does it use a lot more memory then if I just passed the couple things I need?

ex
checkXP(Player* play) // this is a whole object of player
or
checkXP(play->getXP(), play->getLVL()) // the variables I want.

I just realized I may not be able to modify anything from player in the checkXP() function

question 1: does passing the whole object use more memory
question 2: if I passed as just the variables I need, I wont be able to modify anything of object play?

View 1 Replies View Related

C++ :: Variables Not Passing Correctly

Mar 10, 2013

Well I have my program running and the Variables are not passing correctly and the return statements are not returning correctly. Here is the parts that are not working.

#include <iostream>
#include "fight.h"
#include <time.h>
#include "player.h"
#include "stdlib.h"
#include <cstdlib>
using namespace std;

combat A;
combat::combat(void)

[Code] ....

View 11 Replies View Related

C++ :: Passing Variables Between Functions

Jan 29, 2013

I need passing some variables between functions. Here is the first part of the code which does work.

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct CarType {
string maker;

[Code] ....

Now the book says to take the following program and add a member function to the CarType class which prints the values of all of its data members. Add two more data members which are relevant for cars. Add the use of these data members to the program (to the assignment statements for MyCar, to the operator prompt and input inside the getYourCar function, and to the print function you have created).

Here is my code. Whenever I run it, it takes my assigned variables in MyCar and prints those instead of the one which the user is inputting.

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
using namespace std;
struct CarType {
string maker;

[Code] .....

View 3 Replies View Related

C++ :: Reading File Values By Passing Reference To A Function?

Oct 11, 2013

I am trying to read the file which has the values stored in the following pattern

2 4 10 103 2 504 .... and so on

I Have opened the file and then passed the opened file to another function to process it further.

here is my code

#include <iostream>
#include <fstream>
#include <vector>
#include <stdlib.h>

[Code].....

now the problem is when the control exits the "while loop" in the function "readingValues(std::ifstream& myFile)it goes straight to catch block ?

View 9 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved