FAQ Database Discussion Community


Why doesn't this return a new value over and over? java

java,pass-by-reference,pass-by-value
public static int someFunc(int a, int b){ while(a <=b){ a+= 1; return a; } return b; } so i was expecting it to return the new value over and over but it didnt, once i executed the code and saw for myself that, i realised it had something to do...

Pass by Reference issue-Java

java,pass-by-reference,pass-by-value
During the method call compute(ee, temp1, s1, k) from method smaller() the argument value which am passing is not same as the one which am receiving, can someone help me with this issue? *This is my problem statement-Get the least number after deleting k digits from the input number. For...

Passing derived class to base function

c++,inheritance,pass-by-reference,derived-class
I'm having trouble passing a derived class to a function which accepts the base class as argument. The base class is consists of "obstacles" which are to be placed on a "board" void Board::setvalue(int length, int width, Obstacle& obstacle); However, this causes the compiler to give the "no known conversion...

Should I pass a large array by reference or value?

performance,pass-by-reference,rust,pass-by-value
I am building a Game Boy emulator in Rust. I created a readByteFromMemory() function which takes as a parameter an 8KB array which represents the Game Boy's internal memory which was 8KB. I am thinking of two options here: fn readByteFromMemory(internalRAM: [u8;0x2000]) -> u8 or fn readByteFromMemory(internalRAM: &[u8;0x2000]) -> u8...

Bind temporary rvalue to reference lvalue in std::vector constructors

c++,vector,pass-by-reference,lvalue,rvalue
Until now, I thought that we cannot pass a temporary rvalue to a lvalue reference. But just recently, I took a closer look on the fill constructor of std::vector: explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type()); const value_type& val is a reference lvalue...

F# pass by reference

f#,functional-programming,pass-by-reference,out,ref
I'm trying to pass by reference in F#. In C#, it is pretty easy using the ref and out keywords, but it seems in F#, it is not that simple. I just read this: http://davefancher.com/2014/03/24/passing-arguments-by-reference-in-f/, which suggests using a reference cell. (I suppose this means there is no analog to...

Understanding Java Arrays

java,arrays,pass-by-reference,pass-by-value
Please look at the following code : public static void main(String[] args) { Random random = new Random(); int[] array = new int[10]; Arrays.setAll(array, operand -> random.nextInt(10)); System.out.println(Arrays.toString(array)); swap(array, 0, 9); System.out.println(Arrays.toString(array)); } static void swap(int[] array, int i, int j) { int temp = array[i]; // pass by value...

Why can't a function change its argument object's address/reference value?

c++,reference,parameter-passing,pass-by-reference
I learned that in Java and C, you can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points. I thought I could see a different behavior in C++...

Why is “ref” not assigning updated value to the next field?

c#,.net,pass-by-reference,ref,post-increment
I've found a really cool feature of a compilator. However, I cannot understand logic of this behaviour. static int IncrementValue(ref int i) { return i++;} and Main method: static void Main(string[] args) { int a = 2; int b = IncrementValue(ref a); Console.WriteLine(a+b); } The output is 5. My question...

Casting a pointer by reference

c++,casting,parameter-passing,pass-by-reference
I came across something I don't understand well. Let's suppose I want to pass a character pointer to a function that takes a reference to a void pointer. void doStuff(void*& buffer) { // do something } I would usually do something like this : int main() { unsigned char* buffer...

Copied old list reference being changed by new list object modification in python

python,object,multidimensional-array,pass-by-reference,pass-by-value
I'm working on this problem: http://codeforces.com/contest/540/problem/C It seems to be a standard breadth first search on a coordinate plane, so essentially, you can move horizontally or vertically, updating the new position's cell with the character 'X' each time you move In order to solve it, I have to create a...

Python: Tuples getting duplicated when attempting to add them to different lists

python,python-2.7,parameters,tuples,pass-by-reference
I'm really baffled by a problem I've been having with some code to cluster a set of points. I'm using an algorithm to seed a certain number of clusters (3 for example), and then adding points to each cluster. However, after playing with it a bit, I noticed that every...

Why is this structure being sent by parameter?

c,visual-studio,data-structures,parameter-passing,pass-by-reference
I'm using a structure for my DES Algorithm: typedef struct { int size; int capacity; unsigned char *block; }Blocks64; I already did a lot of things to it, so i have some information on the unsigned char. I'm in a function that i call it iterations, and i need to...

Initializing object to an empty list from a reference parameter

c++,pass-by-reference
class ListOfGifts { private: Gift list[50]; int count = 0; public: void suggest(ListOfGifts& affordable, float dollarLimit) const { // how do I initialize affordable to an empty list without a constructor } } Trying to initialize a list from a parameter that is a reference. How can I do this?...

Scope in javascript acting weird

javascript,function,scope,pass-by-reference
Object are passed with their reference in javascript. Meaning change in that object from any where should be reflected. In this case, the expected output was {} for console.log(a) function change(a,b) { a.x = 'added'; a = b;//assigning a as {} to b } a={} b={} change(a,b); console.log(a); //expected {}...

PHP array passed by reference?

php,arrays,typo3,pass-by-reference,pass-by-value
I've been looking for an answer to this issue I have with an array but so far no answer here nor the web. We have a TYPO3 website that has indexed search configured and installed. We crawl records (~60000) using the crawler extension. Everything was configured and running fine but...

Pass a class instance to another class by reference

c++,dependency-injection,pass-by-reference,mbed
I'm trying to pass a single instance of my "Status" class to all my other classes so that they can all set and get the status. I've been trying to do this by passing the "Status" class by reference into my "BaseStation" class. The code compiles fine but when I...

Initializer list reference type safety

c++,compiler-errors,runtime-error,pass-by-reference
Below is some test code I expect to print "Hello world" twice. In fact, it prints "Hello world" once and then throws an Access Exception. The code to print both of the messages are near-identical: #include <iostream> #include <vector> using namespace::std; class VectorWrap1 { public: vector<string>& v; // *** Reference...

Powershell passing 2 arrays by reference to function

arrays,powershell,pass-by-reference
At the moment I am trying to pass in 2 array items by reference to a function I have written which loads data into those arrays, however once this function loses scope the arrays appear as blank. If I use the ref keyword to pass them into the function the...

C++ Passing Static Array and Dynamic Array By Reference

c++,arrays,pointers,reference,pass-by-reference
To fully understand how pointers, values, and references work, I am making a basic C++ program that attempts to tamper with some static and dynamic arrays and understand exactly how they should be passed in. First I generate a static array of 3 elements. I then pass it into a...

Java Pass-by-reference not working?

java,variables,reference,pass-by-reference
I'm trying to make this little game in Java but I seem to have stumbled upon a variable reference problem. My Entity class, which Player extends from, keeps a variable of type Dimension. This Dimension gets set via the constructor of the Entity class like so: protected Dimension dimension; public...

VBA Pass Array By Reference and Modify Contents

arrays,vba,function,pass-by-reference,subroutine
VBA question. I'm using it to make Solidworks macros, but that's not important. Can someone explain the syntax to pass an array (1-Dimensional of type Double, with length of three) to a subroutine or function so I can modify the contents. I know that they have to be passed by...

Function parameter turns into Object's Name instead of its reference

javascript,jquery,json,string,pass-by-reference
this is my JSON structure: var json = { procedure: { id: "content", child: { 154: { class: "sequence nest", text: "LED Ausgeben", id: 154 } } } }; For some reason prop in for (var prop in scope.child){} is only a string instead of the object scope.child.154 as you...

Access violation on pointer

c++,pointers,pass-by-reference
In this code, I am trying to convert a decimal number to binary. (Yes, I am aware that such a function exists -- I was trying to reinvent the wheel as an exercise.) Because I am using a function toBinNum() to convert the number, I wanted to pass an empty...

Passing Incorrect Value to Javascript Function

javascript,php,pass-by-reference,truncation
I am attempting to pass a string '0541210022-0' to a popup window through a Javascript method. When I view the number in my popup window it shows up as 11575826. Can someone please help me determine why this value is changing? I will add code as well as screen shots....

Referencing a variable in a function c++

c++,c++11,pass-by-reference
I'm trying to make sure that I understand what the use of the ampersand to reference a variable is. I know other similar questions have been asked but I would like to see if the code example I give uses it correctly. example code: // function prototype GetBalance(float &balance); int...

How to pass a function in another function with variadic arguments with javascript? [duplicate]

javascript,function,closures,pass-by-reference
This question already has an answer here: Calling dynamic function with dynamic parameters in Javascript 9 answers I have a pre-process function, here's an example function function preprocess (msg, fct) { alert(msg); fct(???); } I need to execute the function fct in the preprocess function, but fct not always...

Can assignment from a const_iterator dereference cause undefined behaviour?

c++,pointers,pass-by-reference,undefined-behavior,const-iterator
This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...

Socket connect() function explanation in C++/ Reference operator and Pointers

c++,c,sockets,pointers,pass-by-reference
I'm new to programming and would like a better understanding of this socket function connect(). I've read many descriptions but I couldn't understand this syntax: int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen) Description: The addr argument is a pointer to a structure specifying the address to which this socket...

Swap entire arrays in Javascript

javascript,arrays,pass-by-reference,pass-by-value
When I try to make a function to swap 2 arrays, the original arrays are left unaltered. function swap(x, y) { var temp = x; x = y; y = temp; } u=[1, 0]; v=[0, 1]; swap(u, v); console.log(u); console.log(v); This results in u as [1, 0] and v as...

Inability to pass values in variable between inner and outer for loops python 3.3

for-loop,global-variables,pass-by-reference,nested-loops,python-3.3
I'm attempting utilizing TeamTreehouse learning subscription & this Starting Out With Programming Logic And Design book to attempt learning programming & python. Please don't shoot to kill me I'm having difficulty with repetition structures! Goal: I'm attempting to collect input from a user in the outer for loop. The inner...

param value with different passing mechanism

c++,pass-by-reference,pass-by-value
int f(float i, float j, float k) { float x=i; i=j; j=k; k=x;} main(){ float x=5; y=10 z=25; if(...){ f(x,y,z); } else{ f(y,z,y); /* what's x,y,z after this line using call-by-reference and call-by-name mechanism*/ } } I think I have a pretty good understand about these three passing mechanism. After...

Why do these blocks of code behave differently?

perl,pass-by-reference,subroutine,pass-by-value,pass-by-pointer
I am new to Perl, and I cannot figure this out. I have two seemingly identical sets of code, but one subroutine updates the value while another does not. In the first set of code, my understanding is that the reference to an array is passed, then the value at...

C++: Pointer vs Pointer of Pointer to insert a node in a Binary Tree

c++,pointers,visual-studio-2012,pass-by-reference,dev-c++
I was creating a function to insert a element in a binary tree and, first, i did the following on Visual Studio 2012: void Insert(Nodo *root, int x){ if(root == NULL){ Nodo *n = new Nodo(); n->value = x root = n; return; } else{ if(root->value > x) Insert(&(root)->left, x);...

How to implement a list of references in python?

python,reference,pass-by-reference
I'm trying to model a collection of objects in python (2). The collection should make a certain attribute (an integer, float or any immutable object) of the objects available via a list interface. (1) >>> print (collection.attrs) [1, 5, 3] >>> collection.attrs = [4, 2, 3] >>> print (object0.attr ==...

How literal are passed in template function

c++,templates,pass-by-reference
#include <iostream> using namespace std; template <typename T> void fun(const T& x) { static int i = 10; cout << ++i; return; } int main() { fun<int>(1); // prints 11 cout << endl; fun<int>(2); // prints 12 cout << endl; fun<double>(1.1); // prints 11 cout << endl; getchar(); return 0;...

Passing a function to a function in C++

c++,function,pass-by-reference
I have a root finding function with the signature: double root_find(double f(double), ...) (the ellipsis just meaning that there are some other arguments that aren't relevant to this question.) I can also declare the function with the signature: double root_find(double(& f)(double), ...) Either way, it works. With the second signature...

Who should clear a vector retrieved by reference?

c++,vector,pass-by-reference
Let's say I have this very simple code: std::vector<int> getVector( int size ) { std::vector<int> res; for ( size_t i = 0; i != size; ++i ) res.push_back( i* 23 ); return res; } int main () { std::vector<int> v; v = getVector(10); std::cout << "Size1 is " << v.size()...

Const keyword in function with an *& argument.

c++,const,pass-by-reference
can you please explain why in the following code: #include <iostream> void fun(char * const & x){(*x)++;} int main(){ char txt[100]="kolokwium"; fun(txt); std::cout << txt <<"\n"; } keyword const is needed for code to compile? If I remove it I get: invalid initialization of non-const reference of type ‘char*&’ from...

What is the correct way to receive a pointer to a C-style string as an argument and be able to allocate memory or modify it?

c++,pass-by-reference,cstring,pass-by-pointer
I have the following method signature: int get_name(char* &name_out); What I'd like to be able to do is allocate memory that is the size of name for name_out and then copy the contents of name into name_out. Or would it be better to change it to: int get_name(char &name_out[], int...

Safe to return const & to object passed by const &?

c++,c++11,pass-by-reference
When compiling the following code with clang-3.5 to the C++11 standard: const String& XMLAttributes::getValueAsString(const String& attrName, const String& def) const { return (exists(attrName)) ? getValue(attrName) : def; } I get the following warning: warning: returning reference to local temporary object [-Wreturn-stack-address] return (exists(attrName)) ? getValue(attrName) : def; ^~~ note: binding...

Qt:signal slot pass by const reference

c++,qt,pass-by-reference,signals-slots,pass-by-value
Many qt examples did the following things: signal: passByConstRef(const QImage &) slot: receivedByConstRef( const QImage &) They are connected through queued connection in different threads. In thread 1: {QImage image; image = fromData(...); emit passByConstRef(image); } In thread 2: receivedByConstRef(const QImage& image){ ... pixmap = fromImage(image); ... } Since the...

What operators do I have to overload to see all operations when passing an object to a function?

c++,operator-overloading,pass-by-reference,pass-by-value,pass-by-pointer
I would like to write a piece of code that shows all copy/assignment/delete etc. operations that are done on the object when passing it to a function. I wrote this: #include <iostream> class A { public: A(){std::cout<<"A()"<<std::endl;} void operator=(const A& a ){std::cout<<"A=A"<<std::endl;} A(const A& a){std::cout<<"A(A)"<<std::endl;} ~A(){std::cout<<"~A"<<std::endl;} }; void pv(A a){std::cout<<"pv(A...

Passing reference from Python to c++ function wrapped with swig for return value

c++,python-3.x,pass-by-reference,swig
Disclaimer, I am a swig and python noob I have my own c++ library and I am wrapping it to use in python with swig. My c++ class is like this: public MyCppClass() { public: void MyFunction(char* outCharPtr, string& outStr, int& outInt, long& outLong) { outCharPtr = new char[2]; outCharPtr[0]...

Determining variables referencing the same value in VS 2013 debugger

c#,debugging,visual-studio-2013,pass-by-reference,watch
While stepping through in Visual Studio 2013 debugger, is there a way to find out, for a currently watched variable, which other variable/field is it currently referencing? In a classic example below, is it possible to determine at the last line, that f2.bar is actually referencing f1.bar? Alternatively, would there...

Passing a Truncated Vector by Reference

c++,pointers,vector,pass-by-reference
I'm trying to figure out if there's a way to pass a truncated vector by reference so that it still changes the original vector. Here's a simplified example of what I'm trying to do. I want the vector x = { 1, 1, 1, 1, 1, 1, 1, 1, 1,...

R / R Shiny - global dataframes array (assigned by reference)?

r,pass-by-reference,shiny
I have a dataframe df1, and subset it to df1sub and display it in an R shiny renderPlot() call. Similarly, I have df2, and I subset it to df2sub, and render it in R shiny via a separate renderPlot() call. Btw these subsets are created based on user choices in...

Can we use pass by reference in java? If No How does java.util.Arrays.sort works?

java,pass-by-reference,pass-by-value
I used to think Java supports both pass by value and passby reference but i came accross many discussions like Java is always pass by value, with no exceptions, ever . Java is always pass-by-value Java always passes arguments by value NOT by reference. Java passes references by value.So you...

Object passed by reference will not exist. Swift

ios,swift,reference,pass-by-reference
I have an array. var array:[customType] = [] // pseudo code func Generate_New_Array(){ //initialization of generatedNewArray array = generatedNewArray for (index,element) in array{ async_process({ Update_Data_From_Web(&array[index]) }) } }) } func Update_Data_From_Web(inout object:customType){ download_process{ object = downloadedData } } The question is , what will should I do if I call...

Set the value of an integer passed by reference

vb.net,pass-by-reference
I am wondering how to set the value of a variable I pass by reference. In this example, I am passing an integer, but in application, it could be a different object. Anyways, here is a short summary of what's happening: Program begins at Sub Main(), and a new form...

Function to copy data in a reference char array

c++,function,pass-by-reference
How can I write in C++ a function who put the data in a char array, I don't how to explain well but I'll write an example void functionCopyData(char& buf){ // get data from a char variable char data1 = "textdata1"; char data2 = "textdata2" // copy data copy(&buf,data1); copy(&buf,data2);...

referencing object inside another object javascript

javascript,object,reference,pass-by-reference
So I have two different set of objects: var house = {}; house["01"] = {hID: "01", neighbh: "00001", name: "house 1"}; house["02"] = {hID: "02", neighbh: "00001", name: "house 2"}; house["03"] = {hID: "03", neighbh: "00002", name: "house 3"}; house["04"] = {hID: "04", neighbh: "00003", name: "house 4"}; var neighborhood...

returned pointer address getting modified when ASLR turned on

c,pointers,pass-by-reference,aslr,char-pointer
I have this piece of C code running on development box with ASLR enabled. It is returning a char pointer (char *) to a function, but somehow few bytes in the returned pointer address are getting changed, printf output below: kerb_selftkt_cache is 0x00007f0b8e7fc120 cache_str from get_self_ticket_cache 0xffffffff8e7fc120 The char pointer...

Changing the pointer inside a function does not reflect outside the function [duplicate]

c,pointers,malloc,pass-by-reference,pass-by-value
This question already has an answer here: How can I allocate memory and return it (via a pointer-parameter) to the calling function? 11 answers void alloco(int *ppa) { int i; printf("inside alloco %d\n",ppa); ppa = (int *)malloc(20); ppa[15] = 9; printf("size of a %d \n", sizeof(ppa)); for(i=0;i<20;i++) printf("a[%d] =...

Passing by reference or use global variable in C

c,pointers,pass-by-reference
Which one is better if I want to modify the value into a function and bring it back to the main? And by saying passing by reference in C, I mean using pointers, like this example. Should I put 'a' as a global variable? #include <stdio.h> #include <conio.h> int sum;...

How to access elements from slice using index which is passed by reference in golang

go,pass-by-reference,slice
I passed a reference of a slice to a function and I am making changes in the slice inside the function. Also I am trying to access an element from the slice using index. It is throwing exception in golang. What is the best way to access an element from...

Pass stream by reference

c,pointers,stream,pass-by-reference,pointer-to-pointer
I am suppose to pass stream, which is a pointer, by reference. So I am passing this as a pointer to a pointer. Can someone please verify my code? int main(int argc, char** argv) { FILE *stream; printf("LINES: %d\n",scan(stream)); } int scan(FILE *(*stream)) { stream = fopen("names.txt", "r"); int ch...

Merge Javascript Objects and All References Pointing at Them

javascript,underscore.js,pass-by-reference
In javascript, variables referring to objects are passed a "copy of the reference". I am struggling with this concept as it relates to merging two objects, and the effect on the references to those objects. Attempting to use underscore's extend, take the following (coffeescript) code: a = { id: 1...

C++ no matching function for call error (defaulting to pass by reference)

c++,graph,compiler-errors,pass-by-reference,dijkstra
I am currently working on a program that uses dijkstra's algorithm with graphs. I was given a function that is supposed to get adjacent vertices of a specified vertex defined here in the Graph class as: template<class VertexType> void Graph<VertexType>::GetToVertices(VertexType vertex, Queue<VertexType>& adjvertexQ) const { int fromIndex; int toIndex; fromIndex...

Pass new variable as reference

php,pass-by-reference
I have a method in a class with this signature: public static function execute($query, $data = array(), &$result = NULL, $onlyOne = true) The point is to execute a SQL query with data (if relevant) and modify the result variable (if set to true) and finally returning only first row...

OpenCV passing values by reference or pointer to callback functions

c++,opencv,callback,pass-by-reference
I'm trying to avoid using global variables in an openCV project (I'll have my supervisor no doubt teach me as to why they are bad rah rah rah :) - but at the moment they seem to be the only way I can get information out of mouse and trackbar...

What Is The Difference Between Passing Parameters By Output And By Reference In C#

c#,methods,parameters,parameter-passing,pass-by-reference
I have been making an effort on C# methods. There are three ways that parameters can be passed to a C# methods. Value parameters : This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside...

Erlang pass-by-reference nuances

erlang,pass-by-reference
9> A = lists:seq(1,10). [1,2,3,4,5,6,7,8,9,10] 13> Fn = fun (L) -> [0|L] end. #Fun<erl_eval.6.90072148> 14> Fn(A). [0,1,2,3,4,5,6,7,8,9,10] 15> A. [1,2,3,4,5,6,7,8,9,10] If erlang internally passes by reference (see this), why does the value of A not reflect the change? What fundamental am I missing about passing-by-reference or erlang?...

References and Casting

java,reference,pass-by-reference,pass-by-value
I'm struggling to understand what I consider a fundamental question in Java. Below the answer is given that line 3 leans to a class cast exception. I can see that originally a1 pointed to an array of object A. But on line 1 doesn't a get set to point to...

Why no significant performance differences for this code with different param passing strategies?

c++,performance,c++11,pass-by-reference
I am trying to write some piece of code and convince myself that pass by value, pass by reference(rvalue and lvalue reference) should have significant impact on performance (related question). And later I came up with this code below and I thought the performance differences should be visible. #include <iostream>...

Odd output when passing file stream by reference

c++,file,pass-by-reference,fileinputstream
In the code below, I am need to read the following from a data file: Dean DeFino 88 98 99 Sally Johnson 78 89 82 Bill Benny 75 79 81 Thomas Billows 78 84 89 However, I get this output: Dean DeFino 88 98 99 hnson 78 89 82-1850860984 32742...