PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label pass-by-reference. Show all posts
Showing posts with label pass-by-reference. Show all posts

Friday, November 4, 2022

[FIXED] Why does passing functions by value work but not by reference

 November 04, 2022     c++, function, lambda, pass-by-reference, temporary-objects     No comments   

Issue

Here I have the code

void foo(std::function<int(int)> stuff){
   //whatever
}

and it is called with

auto fct = [](int x){return 0;};

foo(fct);

Which works great. However, when I change foo to

void foo(std::function<int(int)>& stuff){ // only change is that it is passed by reference
   //whatever
}

The code doesn't compile. Why is this the case? I know we can just pass the object to a reference parameter directly, we don't need the & operator like for pointers. Why can't you pass std::function types by reference?


Solution

You are trying to bind a non-constant reference with a temporary object.

You could use a constant reference.

Here is a demonstration program.

#include <iostream>
#include <functional>

void foo( const std::function<int(int)> &stuff )
{
   int x = 10;

   std::cout << stuff( x ) << '\n';
}

int main()
{
    auto fct = [](int x){return x * 10;};

    foo(fct);
}

The program output is

100

Without the qualifier const you could write for example

#include <iostream>
#include <functional>

void foo( std::function<int(int)> &stuff )
{
   int x = 10;

   std::cout << stuff( x ) << '\n';
}

int main()
{
    auto fct = [](int x){return x * 10;};

    std::function<int(int)> f( fct );

    foo(f);
}

As for the lambda-expression then according to the C++ 17 Standard (8.1.5.1 Closure types)

1 The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.



Answered By - Vlad from Moscow
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 6, 2022

[FIXED] What are the considerations when returning by value vs by reference - Set ADT C

 July 06, 2022     adt, c, pass-by-reference, pass-by-value, set     No comments   

Issue

When looking at the header file of Set ADT in C, I'm trying to understand why was the function setUnion or setIntersection declared that way:

Set setUnion(Set set1, Set set2); 
Set setIntersection(Set set1, Set set2);

I couldn't find the implementation but I'm assuming that inside those functions, we allocate more space and create new set, and then add all the necessary elements. I thought that set1 and set2 are passed by reference, so why not update one of them and save mem allocations and just return some enum that notifies whether the update succeeded or not? (for example we can update the left parameter).

If they're not passed by reference, how can I change the signature in order to do so?

Thank you!


Solution

The Set almost certainly is a pointer hidden behind a typedef, so there is an actual pass by reference of the internal struct which is all that counts.


More often than not one needs to calculate a union or an intersection of two sets without mutating either of them. In fact it is quite probable that

Set result = setIntersection(set1, set2);
freeSet(set1);
set1 = result;

Would not be any less performant than your proposed alternative

setIntersectionInPlace(set1, set2);

Whereas the more common case of calculating an intersection of immutable sets using setIntersectionInplace would need to be written

Set result = setCopy(set1);
setIntersectionInplace(result, set2);

Which would make a needless copy of a set1, which is larger, or equal in size to size of result



Answered By - Antti Haapala -- Слава Україні
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how slicing of derived classes occurs?

 July 06, 2022     c++, inheritance, oop, pass-by-reference, polymorphism     No comments   

Issue

I'm having trouble understanding how slicing occurs? for example, in this piece of code:

class A {
public:
  virtual h() {
    cout << "type A" << endl;
  }
};

class B : public A {
public:
  virtual h() override {
    cout << "type B" << endl;
  }
};

void f(A a) {
  a.h();
}

void g(A& a) {
  a.h();
}

int main() {
  A a1 = B(); // a1 is A and doesn't recognize any B properties
  A *a = new B();
  f(*a);
  g(*a);
}

I noticed that:

  1. variable a1 doens't know it's a B, but variable a does know. I refer this is happening because in variable a1 the assignment to B is by value, in contrst to variable a, where I create a pointer to B.

  2. same thing happens when I pass variable a to different functions - when I pass by value, it thinks it's an A, but when i pass by reference, it thinks it's B.

I would be happy if anyone could give me more extensive and deeper explanation. Thank you in advance!


Solution

In this statement

A a1 = B();

there is used the default copy constructor of the class A because the object a1 has the type A.

This constructor looks like

constexpr A( const A & );

So only subobject of the type A of the object of the class B is copied to the object a1. The table of pointers to virtual functions of the object a1 will contain pointer to its own virtual function.

In this declaration

A *a = new B();

the pointer a points to an object of the type B that contains the table of pointers to virtual functions that in turn contains a pointer to the virtual function of the class B.

So in this call

  g(*a);

the reference to the object of the dynamic type B is passed (the object itself was not changed when it was passed to the function by reference).

So within the function

void g(A& a) {
  a.h();
}.

there will be access to the table of virtual function pointers that contains a pointer to the virtual function of the class B. Here a new object of the class A is not created because the original object is passed by reference.

In this call

  f(*a);

the argument of the function is passed by value. That is there is a copy initialization of the parameter of the function declared like

void f(A a) {
  a.h();
}

So it is in fact the same case as in the declaration

A a1 = B();

considered above.



Answered By - Vlad from Moscow
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What happens if I pass a temporary reference and store it as a class member?

 July 06, 2022     arduino, arduino-c++, c++, constructor, pass-by-reference     No comments   

Issue

I have a class that stores a reference to some kind of application state, which it then mutates during operation:

class Mutator {
    private:
        State& _state;

    public:
        Mutator(State& state);
        ...
};

Mutator::Mutator(State& state) : _state(state) {

}
...

Normally I would create and pass the state like this:

State state;
Mutator mutator(state);

What would happen to the state reference in my Mutator class, if I initialize the Mutator like this:

Mutator mutator(State());

I assume, since the state reference is temporary, the Mutator._state member will point to a memory location which may or may not contain the state value which leads to unpredictable behaviour. Is this correct?


Solution

If you use a reference, then the variable needs to be initialized (as not being NULL) in the constructor. This is safer, since you are assured the reference is really pointing to an existing object.

About

Mutator mutator(State());

This does not make much sense, unless the State object is used only as input for the Mutator constructor; however if it changes the newly created State variable, when the constructor returns and mutator is created, the State() instance is deleted.

Also (see note of NathanOliver below), it is not legal C++ code and not portable.

Update

Test application:

class State {
    public: State() {}
};

class Mutator {
    private:  State& _state;
    public:   Mutator(State& state) : _state(state)  { }
};

void setup() {
    Mutator mutator(State());
}

int main() {
    return 0;
}

The code above compiler and links correctly on an Arduino compiler (1.8.9):

Sketch uses 260 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 8192 bytes for local variables. Maximum is 8192 bytes.


Answered By - Michel Keijzers
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why the modifications of a list inside a function do not change the list?

 July 06, 2022     list, pass-by-reference, python     No comments   

Issue

I am writing a program to remove the duplicated elements from a given sorted list. I wrote function "removeDuplicates" to do some modifications on the list and print the updated list at the end of the function. Since the list is passed by reference, the question is why the changes do not apply on the list outside the function.

def removeDuplicates(nums):
    c = 0
    nums = nums + [nums[-1] + 1]  # add a dummy element to the end of the list
    for i in range(len(nums) - 1):
        if nums[i] != nums[i + 1]:
            nums[c] = nums[i]
            c = c + 1
    nums.pop()
    print(nums)

if __name__ == "__main__":
    nums = [1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 5]
    removeDuplicates(nums)
    print(nums)

Solution

nums = nums + [nums[-1] + 1]  # add a dummy element to the end of the list

Wrong. You specifically create a new list from nums and your new element, and then make your local variable nums point to that new list. You then operate nicely on the new list and exit the function without saving the result.

Try

nums.append(nums[-1] + 1)  # add a dummy element to the end of the list

Output:

[1, 2, 3, 4, 5, 3, 4, 4, 4, 5, 5]


Answered By - Prune
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I simulate pass by reference in Java?

 July 06, 2022     java, pass-by-reference     No comments   

Issue

I'm a complete Java noob. I know that Java treats all parameters as pass by value and there are several other threads where people explain this.

For example, in C++ I can do:

void makeAThree(int &n)
{
   n = 3;
}
int main()
{
   int myInt = 4;
   makeAThree(myInt);
   cout << myInt;
}

Which will output 3. I know that in Java, all parameters are passed by value and thus you can not manipulate the parameter passed in. Is there a standard way to simulate pass by reference in Java? Is there no way to call a function that manipulates a variable passed in? It's tough for me to wrap my head around the idea of there being no way to do this.


Solution

The primary way you can simulate passing a reference is to pass a container that holds the value.

static void makeAThree(Reference<Integer> ref)
{
   ref.set(3);
}

public static void main(String[] args)
{
  Reference<Integer> myInt = new Reference<>(4);
  makeAThree(myInt);
  System.out.println(myInt.get());
}

Since in Java, it is references to objects that are passed by value (the object itself is never passed at all), setting ref to 3 in makeAThree changes the same object referred to by myInt in main().

Disclaimer: Reference isn't a class you can just use with out-of-the-box Java. I'm using it here as a placeholder for any other object type. Here's a very simple implementation:

public class Reference<T> {
    private T referent;

    public Reference(T initialValue) {
       referent = initialValue;
    }

    public void set(T newVal) {
       referent = newVal;
    }

    public T get() {
       return referent;
    }
}

Edit

That's not to say it's great practice to modify the arguments to your method. Often this would be considered a side-effect. Usually it is best practice to limit the outputs of your method to the return value and this (if the method is an instance method). Modifying an argument is a very "C" way of designing a method and doesn't map well to object-oriented programming.



Answered By - Mark Peters
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is a variable used by reference to the set_error_handler function closure undefined?

 July 06, 2022     closures, laravel, pass-by-reference, php, symfony     No comments   

Issue

While reading through the Laravel Framework source code I stumbled upon this code

set_error_handler(function ($type, $msg) use (&$error) {
    $error = $msg;
});

in the move() function of UploadedFile class of the symfony/http-foundation package that Laravel uses Here

Intelephense extension on VSCode raises a warning

Undefined variable '$error'

Deeply apologize for the screenshot of code (just in case this is a bug in the extension and you can't reproduce, please tell me) Sorry

enter image description here

While researching this, I found this answer that passes a closure use to set_error_handler

$that = $this;
set_error_handler( function() use ($that) { $that->customErrorHandler(); } );

My understanding is that customErrorHandler() is a function in the same class or context and it has to be defined outside the call

Searching for similar example on the official docs yield same results, see here

But the UploadedFile class of Symfony only define a private property $error global to the class so shouldn't it be like this?

$error = $this->error;
set_error_handler(function ($type, $msg) use (&$error) {
    $error = $msg;
});

How does this code know to get the $error variable from the property without defining it?*

*that's if it's getting it from there, otherwise...

How is $error passed here? is the undefined warning legit? given the code does actually work (just curious)


Solution

The &$error is making the code work. Basically, it's assigning the $error variable to null when you pass the callable, and then inside, it's setting it to the error message, and used afterwards.

set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$moved = move_uploaded_file($this->getPathname(), $target);
restore_error_handler();

Then it is using the $error variable if it failed to move:

if (!$moved) {
    throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error)));
}

It's the same as:

$error = null;
set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });

Without the &, it will throw an undefined variable notice.

And no the $error variable is not related to the error property.

You can take this code for example:

function executeCallback($callable) {
    $callable();   
}

executeCallback(function () use (&$error) {
    $error = 'This is the error message.';
});

echo $error;

The $error variable is defined in the use (&$error) and used afterward. And the output of the echo would be:

This is the error message.



Answered By - Chin Leung
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why are we not allowed to pass pure reference arguments to std::thread but are allowed to pass raw pointers?

 July 06, 2022     c++, c++11, pass-by-reference, stdthread     No comments   

Issue

Lets say I want to pass some reference argument to the thread - the standard only allows this by using std::ref.

Now lets consider this code that has undefined behaviour (see comments)

    void thread_fun(int& x) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        x = -2;
    }

    int main() {
        {
            int a = 10;
            std::thread t(thread_fun, std::ref(a));
            std::cout << "in main: " << a << '\n';
            t.detach();
        }
        // here thread t may still running and writing to an object "a" which
        // already destroyed is undefined behaviour
        return 0;
    }

Without using std::ref(a) it does not compile - is this some kind protection from undefined behaviour at compile time ?

If it is, then the big question for me is why are we allowed to pass raw pointers to std::thread ?

For example, I can rewrite the same code above to pass a pointer like so:

    void thread_fun(int* x) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        *x = -2;
    }
    //...
    {
        int a = 10;
        std::thread t(thread_fun, &a);
        //...
    }

And this also contains undefined behaviour, but no compile time protection here !?

What is special in case of passing references ??


Solution

What is special in case of passing references ??

The special thing is that passing by reference looks identical at the call site to passing by value.

Every other case you show leaves at least a hint at the call site that you may be doing something risky, without having to read the function prototype.



Answered By - Useless
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I handle an int** in Ada?

 July 06, 2022     ada, c, ffi, memory-address, pass-by-reference     No comments   

Issue

I'm trying to call SDL_LoadWAV using a pre-made binding to the C library from which it comes. SDL_LoadWAV is just a wrapper for SDL_LoadWAV_RW:

function SDL_LoadWAV
 (file      : C.char_array;
  spec      : access SDL_AudioSpec;
  audio_buf : System.Address;
  audio_len : access Uint32) return access SDL_AudioSpec
is
begin
  return SDL_LoadWAV_RW
      (SDL_RWFromFile (file, C.To_C ("rb")),
       1,
       spec,
       audio_buf,
       audio_len);
end SDL_LoadWAV;

Here is the prototype of the function in C:

SDL_AudioSpec* SDL_LoadWAV_RW(SDL_RWops*     src,
                          int            freesrc,
                          SDL_AudioSpec* spec,
                          Uint8**        audio_buf,
                          Uint32*        audio_len)

(See here for more information)

Now as you can see, it passes a Uint8 (unsigned 8-bit integer) array by reference, in the form of a Uint8**. This is causing me a great bit of vexation. Here is the appropriate binding:

function SDL_LoadWAV_RW
 (src       : access SDL_RWops;
  freesrc   : C.int;
  spec      : access SDL_AudioSpec;
  audio_buf : System.Address;
  audio_len : access Uint32) return access SDL_AudioSpec;
pragma Import (C, SDL_LoadWAV_RW, "SDL_LoadWAV_RW");

As you can see, the binding maps the Uint8** to a System.Address. I've tried a couple of tricks to get that data where I want it to go, but nothing seems to work. Right now, my code looks like this (it has a few custom types and exceptions in it):

type Music is new Resource with
record
    --Id : Integer; (Inherited from Resource)
    --Filename : Unbounded_String; (Inherited from Resource)
    --Archive_Name : Unbounded_String; (Inherited from Resource)
    --Zzl_Size : Integer; (Inherited from Resource)
    Audio : access SDL_AudioSpec_Access;
    Length : aliased Uint32;
    Buffer : System.Address;
    Position : Integer := 1;
end record;

overriding procedure Load(Mus : in out Music) is
    Double_Pointer : System.Address;
begin
    Log("Loading music " & To_Ada(Get_Audio_Filepath(Mus)));
    Audio_Load_Lock.Seize;
    if null = SDL_LoadWAV(Get_Audio_Filepath(Mus), Mus.Audio.all, Double_Pointer, Mus.Length'access) then
        raise Audio_Load_Failed with To_String(Mus.Filename) & "&Stack=" & Get_Call_Stack;
    end if;
    Log("Music length =" & Integer'Image(Integer(Mus.Length)));
    declare
        type Sample_Array is array(1..Mus.Length) of Uint8;
        Single_Pointer : System.Address;
        for Single_Pointer'address use Double_Pointer;
        pragma Import(Ada, Single_Pointer);
        Source : Sample_Array;
        for Source'address use Single_Pointer;
        pragma Import(Ada, Source); 
        Dest : Sample_Array;
        for Dest'address use Mus.Buffer;
        pragma Import(Ada, Dest);
    begin
        Dest := Source;
    end;
    Audio_Load_Lock.Release;
end Load;

But, like more or less everything else I've tried, I get a PROGRAM_ERROR/EXCEPTION_ACCESS_VIOLATION when the Load function is executed.

Can anyone figure out how I need to handle this System.Address? Thanks!


Solution

The definition of SDL_LoadWAV_RW says

This function, if successfully called, returns a pointer to an SDL_AudioSpec structure filled with the audio data format of the wave source data. audio_buf is filled with a pointer to an allocated buffer containing the audio data, and audio_len is filled with the length of that audio buffer in bytes.

which means that the called function allocates the required memory and fills it, then returns pointers to the allocated memory and its length.

So the binding you’ve been supplied with isn’t very good Ada.

audio_buf should be an out parameter to an array of bytes, audio_len an out parameter to a Uint32.

As a demo, using this C:

#include <stdlib.h>
void get_data (char **buf, int *len)
{
  *len = 10;
  *buf = malloc(*len);
  for (int j = 0; j < *len; j++) {
    (*buf)[j] = j;
  }
}

this Ada

type Raw is array (Interfaces.Unsigned_32) of Interfaces.Unsigned_8
with Convention => C;

defines an array type (which would occupy 2^32-1 bytes if we actually declared one!), and this

type Raw_P is access all Raw
with Convention => C, Storage_Size => 0;

defines a pointer to such an array. Limiting the storage size to 0 means that we can’t say new Raw_P.

Putting these together,

with Ada.Text_IO; use Ada.Text_IO;
with Interfaces;
procedure Demo is
   type Raw is array (Interfaces.Unsigned_32) of Interfaces.Unsigned_8
   with Convention => C;

   type Raw_P is access all Raw
   with Convention => C, Storage_Size => 0;

   procedure Get_Data (In_Buffer : out Raw_P;
                       Length    : out Interfaces.Unsigned_32)
   with
     Import,
     Convention    => C,
     External_Name => "get_data";

   Allocated : Raw_P;
   Length    : Interfaces.Unsigned_32;

   use type Interfaces.Unsigned_32;
begin
   Get_Data (In_Buffer => Allocated,
             Length    => Length);
   for J in 0 .. Length - 1 loop
      Put (Allocated (J)'Image);
   end loop;
   New_Line;
end Demo;

gives a program which when run results in

$ ./demo
 0 1 2 3 4 5 6 7 8 9
$

----

Recognising that you’re probably stuck with

audio_buf : System.Address;

you could define (or use, if already defined) something like my Raw, Raw_P and say

procedure Get_Data (In_Buffer : System.Address;
                    Length    : out Interfaces.Unsigned_32)
with
  Import,
  Convention    => C,
  External_Name => "get_data";

and then use

Get_Data (In_Buffer => Allocated'Address,
          Length    => Length);


Answered By - Simon Wright
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How add element to a NumPy array in a Python function

 July 06, 2022     numpy-ndarray, pass-by-reference, python     No comments   

Issue

I am trying to create a series of NumPy arrays from a text file using a pool of workers with multiprocessing module.

def process_line(line, x,y,z,t):
    sl = line.split()
    x = np.append(x,float(sl[0].replace(',','')))
    y = np.append(y,float(sl[1].replace(',','')))
    z = np.append(z,float(sl[2].replace(',','')))
    t = np.append(t,float(sl[3].replace(',','')))

def txt_to_HDF_converter(name, path_file):

    #init objects
    x = np.empty(0)
    y = np.empty(0)
    z = np.empty(0)
    t = np.empty(0)
    pool = mp.Pool(4)
    jobs = []

with open(path_file) as f:
    for line in f:
        jobs.append(pool.apply_async(process_line,(line,x,y,z,t)))

#wait for all jobs to finish
for job in jobs:
    job.get()
#clean up
pool.close()

The problem comes when the arrays are assigned in the process_line function, as if arguments where passed by value, at the end of the cycle I end up with arrays with only one element. Any idea of how get around this?


Solution

You are passing the values as part of a tuple in the code here:

        jobs.append(pool.apply_async(process_line,(line,x,y,z,t)))

Then you unpack this tuple implicitly in the function:

def process_line(line, x,y,z,t):

Then you do not change the existing values but instead create new ones with these lines:

    x = np.append(x,float(sl[0].replace(',','')))
    y = np.append(y,float(sl[1].replace(',','')))
    z = np.append(z,float(sl[2].replace(',','')))
    t = np.append(t,float(sl[3].replace(',','')))

Let me repeat this: You do not change the original arrays (as you appear to expect). Instead you just use the old values to create new values which you then assign to the local variables x, y, z, and t. Then you leave the function and forget about the new values. I would say this can never have any effect (also not for the last value) outside of the function.

You have several options of going around this.

  1. Use global variables. This is a quick fix but bad style and in the long run you will hate me for this advice. But if you just need it to work quickly, then this might be your option.

  2. Return your values. After creating the new values, return them somehow and make sure that the next call gets the previously returned values again as input. This is the functional approach.

  3. Pass your values by reference. You can do this by instead of passing x create a one-element list. See the code below on how to do this. Passing references is typical C-style programming and not very Pythonic (but it works). Lots of IDEs will warn you about doing it this way and the typical Python developer will have a hard time understanding what you are doing there. A nicer variant of this is not to use simple lists but to put your data into some kind of object which will be passed by reference.

x_ref = [x]
y_ref = [y]
y_ref = [y]
t_ref = [t]

with open(path_file) as f:
    for line in f:
        jobs.append(pool.apply_async(process_line,(line,x_ref,y_ref,z_ref,t_ref)))

Then the process_line needs to be adjusted to expect references as well:

def process_line(line, x_ref,y_ref,z_ref,t_ref):
    sl = line.split()
    x_ref[0] = np.append(x_ref[0],float(sl[0].replace(',','')))
    y_ref[0] = np.append(y_ref[0],float(sl[1].replace(',','')))
    z_ref[0] = np.append(z_ref[0],float(sl[2].replace(',','')))
    t_ref[0] = np.append(t_ref[0],float(sl[3].replace(',','')))


Answered By - Alfe
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I pass a pointer to a local variable?

 July 06, 2022     c, pass-by-reference     No comments   

Issue

I am having some trouble passing pointers to local variables. When I try printing the printf statement in main(), I get random numbers each time. But when I print it from the parse function, it works fine. I have tried playing around with the pointers and cannot figure it out.

#include <stdio.h>
#include <stdlib.h>


void parse(char record[], int *acct, float *amnt){
            char word1[10], word2[10];
            sscanf(record, "%s %s", word1, word2);

            acct = (int*) malloc(10);
            amnt = (float*) malloc(10);

            *acct = atoi(word1);
            *amnt = atof(word2);

            printf("%d, %.1f\n", *acct, *amnt);
}

int main(){
            FILE *p = fopen("accounts.ssv", "rt");
            char record[20];
            int acct;
            float amnt;

            while (fgets(record, 20, p)){
                    parse(record, &acct, &amnt);
                    printf("%d, %.1f\n", acct, amnt);
            }

            fclose(p);
            return 0;
}

accounts.ssv

20 -50.5
10 60.5
20 30.0

Solution

You are passing pointers to main()'s acct and amnt, but the malloc calls are replacing those pointers with pointers to newly allocated memory.

These lines:

   *acct = atoi(word1);
   *amnt = atof(word2);

write to the newly allocated memory instead of the variables in main().

Try removing the two malloc calls, and the atoi/atof functions will store their result in the main() variables.



Answered By - GandhiGandhi
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to return the reference of a declared vector in the method body?

 July 06, 2022     c++, pass-by-reference, pointers, reference     No comments   

Issue

I have this method :

vector<float> MyObject::getResults(int n = 1000)
{
    vector<float> results(n, 0);
    // do some stuff
    return results;
}

Of course this is not optimized and I want to return a reference of this vector but I cannot simply do this :

const vector<float>& MyObject::getResults(int n = 1000)
{
    vector<float> results(n, 0);
    // do some stuff
    return results;
}

This doesn't work, the vector will be destroy at the end of method because it's a local variable.

So the only solution I found to solve this problem is to create a private vector in MyObject and return a reference to this vector :

const vector<float>& MyObject::getResults(int n = 1000)
{
    this->results.clear();
    this->results.resize(n, 0);
    // do some stuff
    return results;
}

Is this the right way to do that? Do you have any other solution to propose?


Solution

What's most efficient?

Return by value. Don't worry, no copying occurs. This is best practice:

// Use this
vector<float> getResults(int n = 1000);

Why is this? Local variables returned from a function are not copied. They are moved into the location where the return value will be stored:

// Result moved into v; no copying occurs
vector<float> v = getResults(); 

// Result moved into memory allocated by new; no copying occurs
vector<float>* q = new vector<float>(getResults()); 

How does this work?

When a function returns an object, it returns it in one of two ways:

  • In the registers
  • In memory

You can only return simple objects like ints and doubles in the registers. For values returned in memory, the function is passed a pointer to the location that it needs to place the return value.

When you call new vector<float>(getResults());, the following things happen:

  • The computer allocates memory for a new vector
  • It gives the location of that memory to getResults(), along with any other parameters.
  • getResults constructs the vector in that memory, no need to copy.

What about returning a reference to a member variable?

Generally speaking, this is a premature optimization that may not provide much, or any, benefit, and it makes your code more complex and more prone to bugs.

If you assign the output of getResults to a vector, then the data will get copied anyways:

MyObject m; 
vector<float> = m.getResults(); // if getResults returns a const reference, the data gets copied

On the other hand, if you assign the output of getResults to a const reference, this can make managing the lifetime of MyObject much more complex. In the below example, the reference you return is invalidated as soon as the function ends because m gets destroyed.

vector<float> const& evilDoNotUseThisFunction() {
    MyObject m;
    vector<float> const& ref = m.getResults();
    return ref; // This is a bug - ref is invalid when m gets destroyed
}

What's the difference between copying and moving for std::vector?

Copying loops over all the elements of a vector. When a vector is copied, all the data stored by the vector gets copied:

vector<float> a = getVector(); // Get some vector

vector<float> b = a // Copies a

This is equivalent to the following code:

vector<float> a = getVector(); // Get some vector

vector<float> b(a.size()); // Allocate vector of size a

// Copy data; this is O(n)
float* data = b.data();
for(float f : a) {
    *data = f;
    data++;
}

Moving doesn't loop over any elements. When a vector is constructed by move, it's as though it's swapped with an empty vector:

vector<float> a = getVector(); // Get some vector

vector<float> b = std::move(a); // Move a into b

is equivalent to:

vector<float> a = getVector(); // Get some vector

vector<float> b; // Make empty vector (no memory allocated)

std::swap(a, b); // Swap a with b; very fast; this is O(1)

TL;DR: Copying copies all the data in a loop. Moving just swaps out who owns the memory.

How do we know results gets moved? C++11 requires that local variables get moved automatically when they're returned. You don't have to call move.

Does a swap actually occur? In many cases, no. A swap is already cheap, but the compiler can be clever and optimize out the swap entirely. It does this by constructing your results vector in the memory where it'll be returning results. This is called Named Return Value Optimization. See https://shaharmike.com/cpp/rvo/#named-return-value-optimization-nrvo



Answered By - Alecto Irene Perez
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to accept both modifiable and non-modifiable arguments?

 July 06, 2022     c++, pass-by-reference, reference     No comments   

Issue

I have a debugging macro where I give it a float reference, and expect it to modify that variable sometimes, if it can.

#define probe(x) implProbe(#x##GETLINE, (x))

void implProbe(const char * loc, float & x){
    // this signature is a place holder
    ...
    x = 4.f;
}

However, I would also like to use the same macro for temporary variables or literals such as probe(1 + 2) or probe(x + y). The macro wouldn't need to have the same effect in those cases, I don't expect to see an output from it, I only want it to not break.

float var = 0.f;
probe(var);
// var == 4.f

var = 0.f;
probe(var + 2.f);  // this should be legal
// var == 0.f (didn't change)

probe(1.f); // this should be legal

Is there a way to accomplish this?


Solution

Implement two overloaded functions.

void implProbe(const char * loc, float & x){
    ...
    x = 4.f;
}
void implProbe(const char * loc, const float & x){
    ...
}


Answered By - 273K
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to pass object to animation function in JavaScript?

 July 06, 2022     animation, javascript, object, pass-by-reference     No comments   

Issue

I have been trying to make a JavaScript animation of moving circle in HTML Canvas without using global variables. I am using requestAnimationFrame function. Since JavaScript does not support passing variable by reference, I tried creating a Circle class:

class Circle{
  constructor(x, y, dx, dy) //set initial position and velocity of circle
  {
    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
  }
}

function moveCircle(circle, other variables)
{
  //clear canvas
  //calculate new position and velocity using circle.x, etc.
  //save new values to the object
  //draw new circle into the canvas

  requestAnimationFrame(moveCircle);
}

function button()//function called after click on button
{
  //initial settings of canvas, intial condition

  circle = new Circle(x, y, dx, dy);
  moveCircle(circle, other vars);
}

This makes one frame and then throws error "Cannot read property 'x' of undefined". What am I doing wrong? Is there any other way of doing this, while avoiding global variables?


Solution

First of all, you don't need to create a class you can just pass the coordinates in an object or as separate arguments. Secondly you should use Function#bind on requestAnimationFrame to pass the same arguments to next call.

Example using object:

function moveCircle(circle) {
  console.log(circle.x);
  if (circle.x) {
    circle.x -= circle.dx;
    requestAnimationFrame(moveCircle.bind(null, circle));
  }
}

function button() {
  moveCircle({
    x: 500,
    y: 0,
    dx: 20,
    dy: 0
  });
}

button();

Example without object:

function moveCircle(x, dx) {
  console.log(x);
  if (x) {
    requestAnimationFrame(moveCircle.bind(null, x - dx, dx));
  }
}

function button() {
  moveCircle(500, 20);
}

button();



Answered By - nick zoum
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to pass 2d array in python by value and not by reference?

 July 06, 2022     arrays, pass-by-reference, python     No comments   

Issue

I have a 2D array that I need to constantly update and assign to different variables but the update has to take place from the initial array. Since lists are passed by reference and not by value the regular assignment does not work. I tried: list1 = list2[:] which works perfectly fine with a 1D arrays but not with a 2D array.

Has anyone encountered this before?


Solution

Python Shallow and Deep Copy

As you said, this kind of assignment is done by reference and not by value. In order to assign mutable data types like lists, numpy arrays and etc. by value, you have to use Python Copy Module. This module provides you with two shallow and deep copy methods that you should chose one of them according to the type of data which you are going to copy. If the object you are going to copy includes another objects like list, classes and ... in itself, you should use deep copy method otherwise, shallow copy should be used (In the above described problem, it seems shallow copy is what you are looking for).



Answered By - Arashsyh
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why dereference a reference in C? Using & next to *

 July 06, 2022     ampersand, c, pass-by-reference, pointers, scanf     No comments   

Issue

I looked at this and this and this and this and more.

Question is:

A basic C Programming MOOC on EdX is showing how to access a member of a struct within a function, when the struct was passed by pointer. Why in the world are they using & next to *???

They show: scanf("%lf", &(*studptr).aveGrade);

Why not just use studptr.aveGrade in scanf?

(Leaving aside the separate question, "why use scanf at all")

(Was asked for complete example)

void readStudent(struct student *studptr) {
    print("\nEnter a new student record: \n");
    printf("First name: ");
    scanf("%s", (*studptr).firstName);
    printf("Last name: ");
    scanf("%s", (*studptr).lastName);
    printf("Birth year: ");
    scanf("%d", &(*studptr).birthYear);
    printf("Average grade: ");
    scanf("%lf", &(*studptr).aveGrade);
}

Solution

Because & doesn't refer to (*stupdtr), it refers to (*studptr).aveGrade. The . operator has higher precedence.



Answered By - Federico klez Culloca
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the reason why JS push objects by reference?

 July 06, 2022     arrays, javascript, pass-by-reference, reference     No comments   

Issue

What is the reason why Javascript push objects by reference and not by value?

And why this behavior is only for objects and not also for built-in primitives types?

For example:

let x = {a: 10, b: 100 }
let ar = [];

ar.push(x);
x.a = 9;
console.log(ar[0].a); // This print 9, not 10

I think an answer to this question is useful to understand some deep functions about this language.

Thanks in advance.


Solution

Everything in JavaScript is passed by value...

But, those values can be a reference value.

The different seems subtle, but its very important.

For example, if you have a function:

function nukeArray(a) {
  a = [];
}

Then, when you call it, a will receive a value that happens to be a reference. That value is immediately discarded and a is assigned a new reference.

If a was a pure reference, then changing a would also change the value of its caller.

In a language like C you can easily pass a reference -- change the reference -- then the caller's value will be changed as well.

#include <stdio.h>
#include <stdlib.h>

void t(char **t) {
    *t = malloc(50);
}

int main() {
    char *tmp;
    printf("pre: %p\n", tmp);
    t(&tmp);
    printf("post: %p\n", tmp);
}


Answered By - Jeremy J Starcher
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Increment a class Integer references value in java from another method

 July 06, 2022     java, pass-by-reference     No comments   

Issue

package myintergertest;

/**
 *
 * @author Engineering
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //this one does not increment 
        Integer n = new Integer(0);
        System.out.println("n=" + n);
        Increment(n);
        System.out.println("n=" + n);
        Increment(n);
        System.out.println("n=" + n);
        Increment(n);
        System.out.println("n=" + n);
        Increment(n);

        //this one will increment
        MyIntegerObj myInt = new MyIntegerObj(1);
        Increment(myInt);
        System.out.println("myint = " + myInt.get());
        Increment(myInt);
        System.out.println("myint = " + myInt.get());
        Increment(myInt);
        System.out.println("myint = " + myInt.get());

    }

    public static void Increment(Integer n) {
        //NO.  this doesn't work because a new reference is being assigned
        //and references are passed by value in java
        n++;
    }

    public static void Increment(MyIntegerObj n) {
        //this works because we're still operating on the same object
        //no new reference was assigned to n here.
        n.plusplus();   //I didn't know how to implement a ++ operator...
    }
}

The result for all of those is n=0. Integer n is an object and therefore passed by reference, so why isn't the increment reflected back in the caller method (main)? I expected output to be n=0 n=1 n=2 etc...

UPDATE: Notice I updated the code example above. If I'm understanding correctly, Jon Skeet answered the question of why myInt would increment and why n does not. It is because n is getting a new reference assigned in the Increment method. But myInt does NOT get assigned a new reference since it's calling a member function.

Does that sound like I understand correctly lol ?


Solution

No, objects aren't passed by reference. References are passed by value - there's a big difference. Integer is an immutable type, therefore you can't change the value within the method.

Your n++; statement is effectively

n = Integer.valueOf(n.intValue() + 1);

So, that assigns a different value to the variable n in Increment - but as Java only has pass-by-value, that doesn't affect the value of n in the calling method.

EDIT: To answer your update: that's right. Presumably your "MyIntegerObj" type is mutable, and changes its internal state when you call plusplus(). Oh, and don't bother looking around for how to implement an operator - Java doesn't support user-defined operators.



Answered By - Jon Skeet
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is type arrayp[] the same as type* arrayp as parameter of a function?

 July 06, 2022     arrays, c, parameter-passing, pass-by-reference, pointers     No comments   

Issue

Why is f.e. int arrayp[] the same as int* arrayp, as parameter in the definition/declaration of a function?

 int* foo(int arrayp[]){}

A pointer to the first element of an int array passed as argument in the caller.

Like:

 #include <stdio.h>

 int* foo (int arrayp[]);

 int main(void)
 {
    int a[] = { 10,5,4,2,1 };
    int *p;

    p = foo(a);

    printf("%d",*p);

    return 0;
 }

 int* foo(int arrayp[])
 {
     *arrayp = 0;
     return arrayp;          
 }

Why is int arrayp[] a pointer to the first element of an array of type int? IMHO I think this is very confusing. Some people may think that they passing an entired array (pass by value) with this expression.


Solution

In function parameter types, arrays are implicitly adjusted to the pointer they would decay to.

Thus, these function declaration pairs, for example, are compatible:

void foo(int a[]);
void foo(int *a);  //compatible declaration

void bar(int a[][2][3]);
void bar(int (*a)[2][3]);  //compatible declaration

Dennis Ritchie (the language author) explains this confusing rule in https://www.bell-labs.com/usr/dmr/www/chist.html

Moreover, some rules designed to ease early transitions contributed to later confusion. For example, the empty square brackets in the function declaration

int f(a) int a[]; { ... } are a living fossil, a remnant of NB's way of declaring a pointer; a is, in this special case only, interpreted in C as a pointer. The notation survived in part for the sake of compatibility, in part under the rationalization that it would allow programmers to communicate to their readers an intent to pass f a pointer generated from an array, rather than a reference to a single integer. Unfortunately, it serves as much to confuse the learner as to alert the reader.

(Note: Chist.html uses a K&R style function definition. A prototyped equivalent of the above function definition would be int f( int a[]){ ... }.)

In short, the rule exists mainly to ease transition from B to C and to allow the programmer to signal to the reader that a pointer to the first element of an array is expected, rather than just a pointer to a single element (and do so without having to use a comment).

Function-typed parameters are also adjusted to pointers in a similar way.

void takeFuncPtr(void Func(void));
void takeFuncPtr(void (*Func)(void)); //compatible declaration

A perhaps more deeper question would be "why do arrays decay to pointers at all in C"?. The linked document provides an answer to that question as well:

... These semantics represented an easy transition from B, and I experimented with them for some months. Problems became evident when I tried to extend the type notation, especially to add structured (record) types. Structures, it seemed, should map in an intuitive way onto memory in the machine, but in a structure containing an array, there was no good place to stash the pointer containing the base of the array, nor any convenient way to arrange that it be initialized. For example, the directory entries of early Unix systems might be described in C as

struct { int inumber; char name[14]; };

I wanted the structure not merely to characterize an abstract object but also to describe a collection of bits that might be read from a directory. Where could the compiler hide the pointer to name that the semantics demanded? Even if structures were thought of more abstractly, and the space for pointers could be hidden somehow, how could I handle the technical problem of properly initializing these pointers when allocating a complicated object, perhaps one that specified structures containing arrays containing structures to arbitrary depth? The solution constituted the crucial jump in the evolutionary chain between typeless BCPL and typed C. It eliminated the materialization of the pointer in storage, and instead caused the creation of the pointer when the array name is mentioned in an expression. The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

...



Answered By - PSkocik
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How does reference to pointer exactly work in C++, and when do we need them (in the case of linked list)

 July 06, 2022     c++, pass-by-reference, pointers, singly-linked-list     No comments   

Issue

I know that pointers hold the address of a variable. And references point to the same address in the symbol table (that is, the same address of the variable, that they are assigned to).

My question is, how do reference to pointers exactly work. And when do we need them, as opposed to using pointer alone (and not using reference to pointer). It will be helpful if you could explain me the use of reference to pointer, with respect to a singly linked list.

I have the following code that deletes the head pointer of a linked list using a function:

struct Node
{
    int data;
    Node* next;
};

struct Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->next = nullptr;
    return temp;
}

Node* deleteHead(Node* &head)
{
    if (head)
    {
        Node* temp = head;
        head = head->next;
        delete temp;
    }
    return head;
}

int main()
{
    Node* head = newNode(1);
    head->next = newNode(6);
    head->next->next = newNode(4);
    head->next->next->next = newNode(8);

    head = deleteHead(head);
    Node* temp = head;
    while (temp != nullptr)
    {
        cout << temp->data << " " << endl;
        temp = temp->next;
    }
    return 0;
}

In the deleteHead(Node* &head) function, the function takes the argument, Node* &head. But, the code works fine, even when the argument is Node* head. for what cases do we need to pass Node* & instead of Node* in a linked list?

Following is the deleteHead(Node* &head) function above, which works the same, if we only use Node* head as the argument, instead of Node* &head -

Function that works the same with Node* and Node* &


Solution

You pass a pointer by reference for the same reason you pass a non-pointer by reference: To let the function modify its value.

Let me use a simpler example

#include <iostream>

void foo(int*& x) {
    *x = 42;        // change the value of the int x points to
    x = nullptr;    // change the value of x
}

The first line modifies the value x points to (but it does not modify x). The second line modifies x itself.

int main() {
    int y = 42;
    int* y_ptr = &y;
    foo(y_ptr);
    if (y_ptr == &y) std::cout << "cannot happen";
}

Because we set x = nullptr, y_ptr will not point to y anymore after the call.

Now if we modify foo to not take a reference we get:

#include <iostream>

void foo(int* x) {
    *x = 42;        // change the value of the int x points to
    x = nullptr;    // change the value of x
}

Again the first line modifies the int pointed to by x. However, now the second line only has an effect on x local to the function.

int main() {
    int y = 42;
    int* y_ptr = &y;
    foo(y_ptr);
    if (y_ptr == nullptr) std::cout << "cannot happen";
}

The value of y_ptr cannot change by passing it to foo, because it is passed by value.

In your code you have

Node* deleteHead(Node* &head)
{
    if (head)
    {
        Node* temp = head;
        head = head->next;
        delete temp;
    }
    return head;
}

And when you write head = deleteNode(head) two things are happening:

  • the function modifies head (because it is passed by reference) to point to head->next.
  • the function also returns this "new" head (pointing to head->next) and that is assigned to head.

So you basically asign to headtwice. Because head is passed by reference deleteNode would do the right thing without using the return value:

deleteNode(head);  // this already does modify head 

...or put the other way around: If you return the "new" head (head->next) from the fucntion and assign it to head, then it does not matter if you pass the pointer by reference, because the assignment done inside the function has the same effect.

Your code is similar to

int* bar(int*& x) {
   x = nullptr;
   return x;
}

and then call it via

int y = 42;
int* y_ptr = &y;
y_ptr = bar(y_ptr);

where the same effect could be achieved by not using the returned value bar(y_ptr). Or the same without pointers (because pointers really make no difference here):

int moo(int& x) {
    x = 0;
    return x;
}

int x = 42;
x = moo(x);     // same as `moo(x)`

PS: You dont need both (return the pointer and assign it already in the function), so better make the function return void.



Answered By - 463035818_is_not_a_number
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing