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?
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 )
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?
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{
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
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.
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.
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++.
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);
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?
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?
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;
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.
Basically I'm trying to pass an object as a reference to the template function, rather than a copy as it's seeing. I'm needing to do this without editing Obj::Call to accommodate a reference as its first parameter, as it'd break other calls.
You'll notice in the following code the object will be destroyed upon passing, while the object defined is still in-scope due to the infinite end loop.
#include <iostream> #include <string> using namespace std; class Obj { public: string name; Obj(string name): name(name) {cout << "create " << this << endl;}
[code]....
In the past I tried ref(), which appeared to stop this happening, however it created a blank copy of the object instead.
I have a school project in which need to create a function that takes a File Object as a Reference Parameter. Supposedly, it should allow me to read the first piece of data from others separated by a space from a file. The later be able to continue reading from the next piece of data.
I know how to set things up to read from the data file, such as using
I have a struct called Array and I'm to create a function to create a dynamic array that's fill with randomly generated integers from 0 to 50 (inclusive) and a function to destroy the array for freeing its memory. Below the code that I have written so far.
Code:
* Struct */ typedef struct {int *pArray; //the dynamic array int length; //the size of the dynamic array}Array; /* Function to create a dynamic array */ Array *initializeArray (int length) {int i; }
Im trying to reference my array in another function but i keep getting errors.
void player::store() { int menuChoice; int amountChoice = 0; int items[4] = {0,0,0,0}; string inv;
[Code]...
errors
C:UsersChayDesktopDinosaur ArenaMainGame.h|81|error: declaration of 'items' as array of references| C:UsersChayDesktopDinosaur ArenaMainGame.h|81|error: prototype for 'void player::backpack(...)' does not match any in class 'player'| C:UsersChayDesktopDinosaur Arenaplayer.h|24|error: candidate is: void player::backpack()|
I wanted to print the values of a array from a function by passing the array as well as the number of elements to be read. For a single dimensional array, this is how i have written it. It's pretty straight forward. I want to read 5 elements from the 5th element in the array.
Code: #include<stdio.h> void display(int array[],int size) { int i;
[Code]....
With this code I want to print the five elements from the element present in [0][4].
But shows an error that
Code: D:BennetCodeblocks CLearning CSingleDimentionalArray.c||In function 'main':| D:BennetCodeblocks CLearning CSingleDimentionalArray.c|18|warning: passing argument 1 of 'display' from incompatible pointer type [enabled by default]| D:BennetCodeblocks CLearning CSingleDimentionalArray.c|2|note: expected 'int (*)[10]' but argument is of type 'int *'| ||=== Build finished: 0 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
I know when you pass a array as an argument it gets decomposed into a pointer, but with a multi-dimensional array this is not the case. how this works for mult- dimensional array's?